分布式服务器框架之Servers.Core库中实现 MongoEntityBase 实现阻塞 异步对MongoDB的增删改查

简介: YFMongoDBModelBase类是个模板类,对模板参数进行了约束YFMongoEntityBase,必须要继承YFMongoEntityBase

YFMongoDBModelBase类是个模板类,对模板参数进行了约束YFMongoEntityBase,必须要继承YFMongoEntityBase


using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
namespace Servers.Core
{
    // MongoDBModel 基类
    //要继承YFMongoEntityBase
    public abstract class YFMongoDBModelBase<T>
        where T : YFMongoEntityBase, new()
    {
        #region 子类需要实现的属性
        //MongoDB的客户端类(MongoDB是服务器,链接MongoDb的服务器就变成了客户端了)
        protected abstract MongoClient Client
        {
            get;
        }
        //数据库名称
        protected abstract string DatabaseName
        {
            get;
        }
        //集合名称(对应的是Mysql或者是SqlServer中的Table)
        protected abstract string CollectionName
        {
            get;
        }
        //是否记录错误日志(这个一般都要开启的吧?)
        protected virtual bool CanLogError
        {
            get { return false; }
        }
        #endregion
        #region 获取文档集合 GetCollection
        //写了类型之后是会把Mongo中的二进制数据实例化成这个entity类??
        private IMongoCollection<T> m_Collection = null;
        //获取文档集合(get某个类型的Collection,相当于获取某个类型的Table,不过怎么感觉那么奇怪)
        public IMongoCollection<T> GetCollection()
        {
            try
            {
                if (null == m_Collection)
                {
                    IMongoDatabase database = Client.GetDatabase(DatabaseName);
                    m_Collection = database.GetCollection<T>(CollectionName);
                }
                return m_Collection;
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:log类还没写,后面有了log类之后这里的log打印要补上
                }
                else
                {
                    throw e;
                }
                return null;
            }
        }
        #endregion
        #region GetEntity 根据编号查询实体
        //根据编号查询实体
        public T GetEntity(long YFId)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                FilterDefinition<T> filter = Builders<T>.Filter.Eq("YFId", YFId);
                return collection.Find(filter).FirstOrDefault();
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:记录错误日志
                }
                else
                {
                    throw e;
                }
                return null;
            }
        }
        //异步根据编号查询实体
        public async Task<T> GetEntityAsync(long YFId)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                FilterDefinition<T> filter = Builders<T>.Filter.Eq("YFId", YFId);
                return await collection.Find(filter).FirstOrDefaultAsync();
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:记录错误日志
                }
                else
                {
                    throw e;
                }
                return null;
            }
        }
        //根据条件查询实体
        public T GetEntity(FilterDefinition<T> filter)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                return collection.Find(filter).FirstOrDefault();
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
                return null;
            }
        }
        //异步根据条件查询实体
        public async Task<T> GetEntityAsync(FilterDefinition<T> filter)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                return await collection.Find(filter).FirstOrDefaultAsync();
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
                return null;
            }
        }
        #endregion
        #region 查询数量
        //查询数量(传进去一个规则策略,寻找符合规则的集合数量)
        public long GetCount(FilterDefinition<T> filter)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                return collection.CountDocuments(filter);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else 
                {
                    throw e;
                }
                return 0;
            }
        }
        //异步查询数量
        public async Task<long> GetCountAsync(FilterDefinition<T> filter)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                return await collection.CountDocumentsAsync(filter);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
                return 0;
            }
        }
        #endregion
        #region 根据条件查询数据集合
        /// <summary>
        /// 异步根据条件查询数据集合
        /// </summary>
        /// <param name="filter">过滤条件</param>
        /// <param name="sort">排序</param>
        /// <param name="skip">跳过</param>
        /// <param name="limit">限制数量</param>
        public List<T> GetList(FilterDefinition<T> filter, out long count, string[] field = null, SortDefinition<T> sort = null)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                count = collection.CountDocuments(filter);
                //不指定查询字段???
                if (field == null || field.Length == 0)
                {
                    if (sort == null) 
                        return collection.Find(filter).ToList();
                    //如果有排序规则,进行排序
                    return collection.Find(filter).Sort(sort).ToList();
                }
                //这个的直接翻译叫投影,可以理解成一种投影关系,包含这个名字的(但是不知道include是查找所有的json字符串吗?)
                List<ProjectionDefinition<T>> fieldList = new List<ProjectionDefinition<T>>();
                for (int i=0;i< fieldList.Count;++i)
                {
                    fieldList.Add(Builders<T>.Projection.Include(fieldList[i].ToString()));
                }
                ProjectionDefinition<T> projection = Builders<T>.Projection.Combine(fieldList);
                //可空类型,不为空就调用Clear
                fieldList?.Clear();
                //没排序规则,就不排序
                if (sort == null)
                    return collection.Find(filter).Project<T>(projection).ToList();
                //三重规则??mmp
                return collection.Find(filter).Sort(sort).Project<T>(projection).ToList();
            }
            catch(Exception e) 
            {
                if (CanLogError)
                {
                }
                else 
                {
                    throw e;
                }
                count = 0;
                return null;
            }
        }
        /// <summary>
        /// 异步根据条件查询数据集合
        /// </summary>
        /// <param name="filter">过滤条件</param>
        /// <param name="sort">排序</param>
        /// <param name="skip">跳过</param>
        /// <param name="limit">限制数量</param>
        public async Task<List<T>> GetListAsync(FilterDefinition<T> filter,string[] field = null, SortDefinition<T> sort = null)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                //count = collection.CountDocuments(filter);
                if (field == null || field.Length == 0)
                {
                    if (sort == null)
                        return await collection.Find(filter).ToListAsync();
                    //如果有排序规则,进行排序
                    return await collection.Find(filter).Sort(sort).ToListAsync();
                }
                //这个的直接翻译叫投影,可以理解成一种投影关系,包含这个名字的(但是不知道include是查找所有的json字符串吗?)
                List<ProjectionDefinition<T>> fieldList = new List<ProjectionDefinition<T>>();
                for (int i = 0; i < fieldList.Count; ++i)
                {
                    fieldList.Add(Builders<T>.Projection.Include(fieldList[i].ToString()));
                }
                ProjectionDefinition<T> projection = Builders<T>.Projection.Combine(fieldList);
                //可空类型,不为空就调用Clear
                fieldList?.Clear();
                //没排序规则,就不排序
                if (sort == null)
                    return await collection.Find(filter).Project<T>(projection).ToListAsync();
                return await collection.Find(filter).Sort(sort).Project<T>(projection).ToListAsync();
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                }
                else
                {
                    throw e;
                }
                //count = 0;
                return null;
            }
        }
        /// <summary>
        /// 查询分页集合
        /// </summary>
        /// <param name="filter">过滤器</param>
        /// <param name="pageSize">每页数量</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="count">总数量</param>
        /// <param name="field">字段</param>
        /// <param name="sort">排序</param>
        public List<T> GetListByPage(FilterDefinition<T>filter,int pageSize,int pageIndex,out long count,string[] field=null,SortDefinition<T>sort=null)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                count = collection.CountDocuments(filter);
                //不查询指定字段
                if (field == null || field.Length == 0)
                {
                    if (sort == null)
                        return collection.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
                    //如果有排序规则进行排序
                    collection.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
                }
                //制定查询字段
                List<ProjectionDefinition<T>> fieldList = new List<ProjectionDefinition<T>>();
                for (int i = 0; i < field.Length; ++i)
                {
                    fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));    
                }
                ProjectionDefinition<T> projection  =Builders<T>.Projection.Combine(fieldList);
                fieldList?.Clear();
                //不排序
                if(sort==null)
                    return collection.Find(filter).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
                //先投影再排序?这样投影出来的不久不会参与排序了嘛?
                return collection.Find(filter).Sort(sort).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
                count = 0;
                return null;
            }
        }
        /// <summary>
        /// 异步查询分页集合
        /// </summary>
        /// <param name="filter">过滤器</param>
        /// <param name="pageSize">每页数量</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="field">字段</param>
        /// <param name="sort">排序</param>
        public async Task<List<T>> GetListByPageAsync(FilterDefinition<T> filter, int pageSize, int pageIndex, string[] field = null, SortDefinition<T> sort = null)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                //count = collection.CountDocuments(filter);
                //不查询指定字段
                if (field == null || field.Length == 0)
                {
                    if (sort == null)
                        return await collection.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
                    //如果有排序规则进行排序
                    collection.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
                }
                //制定查询字段
                List<ProjectionDefinition<T>> fieldList = new List<ProjectionDefinition<T>>();
                for (int i = 0; i < field.Length; ++i)
                {
                    fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
                }
                ProjectionDefinition<T> projection = Builders<T>.Projection.Combine(fieldList);
                fieldList?.Clear();
                //不排序
                if (sort == null)
                    return await collection.Find(filter).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
                return await collection.Find(filter).Sort(sort).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
                //count = 0;
                return null;
            }
        }
        #endregion
        #region Add添加实体
        //添加实体
        public void Add(T entity)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                collection.InsertOne(entity);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                }
                else
                {
                    throw e;
                }
            }
        }
        //异步添加实体
        public async Task AddAsync(T entity)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                await collection.InsertOneAsync(entity);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                }
                else
                {
                    throw e;
                }
            }
        }
        #endregion
        #region AddMany 添加多个实体
        //添加多个实体
        public void AddMany(List<T> lst)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                collection.InsertMany(lst);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:   
                }
                else
                {
                    throw e;
                }
            }
        }
        //异步添加多个实体
        public async Task AddManyAsync(List<T> lst)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                await collection.InsertManyAsync(lst);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:   
                }
                else
                {
                    throw e;
                }
            }
        }
        #endregion
        #region Update 修改实体
        //修改实体
        public void Update(T entity)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                FilterDefinition<T> filter = Builders<T>.Filter.Eq("YFId", entity.YFId);
                collection.FindOneAndReplace(filter,entity);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
            }
        }
        //异步修改实体
        public async Task UpdateAsync(T entity)
        {
            try
            {
                IMongoCollection<T> collection = GetCollection();
                FilterDefinition<T> filter = Builders<T>.Filter.Eq("YFId", entity.YFId);
                await collection.FindOneAndReplaceAsync(filter, entity);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
            }
        }
        #endregion
        #region 删除实体
        //删除实体
        public void Delete(long YFId)
        {
            try
            {
                T entity = GetEntity(YFId);
                if (null != entity)
                {
                    entity.Status = DataStatus.Delete;
                    Update(entity);
                }
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
            }
        }
        //异步删除实体
        public async Task DeleteAsync(long YFId)
        {
            try
            {
                T entity = await GetEntityAsync(YFId);
                if (null != entity)
                {
                    entity.Status = DataStatus.Delete;
                    await UpdateAsync(entity);
                }
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO:
                }
                else
                {
                    throw e;
                }
            }
        }
        #endregion
        #region 删除所有文档
        public void DeletaAll()
        {
            try
            {
                //删库跑路了??drop这个table
                IMongoDatabase database = Client.GetDatabase(DatabaseName);
                database.DropCollection(CollectionName);
                //drop了为啥还要再create一下?为了完全覆盖内存吗???
                database.CreateCollection(CollectionName);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO
                }
                else 
                {
                    throw e;
                }
            }
        }
        public async Task DeletaAllAsync()
        {
            try
            {
                IMongoDatabase database = Client.GetDatabase(DatabaseName);
                await database.DropCollectionAsync(CollectionName);
                await database.CreateCollectionAsync(CollectionName);
            }
            catch (Exception e)
            {
                if (CanLogError)
                {
                    //TODO
                }
                else
                {
                    throw e;
                }
            }
        }
        #endregion
    }
}
相关文章
|
NoSQL MongoDB 微服务
微服务——MongoDB实战演练——文章评论的基本增删改查
本节介绍了文章评论的基本增删改查功能实现。首先,在`cn.itcast.article.dao`包下创建数据访问接口`CommentRepository`,继承`MongoRepository`以支持MongoDB操作。接着,在`cn.itcast.article.service`包下创建业务逻辑类`CommentService`,通过注入`CommentRepository`实现保存、更新、删除及查询评论的功能。最后,新建Junit测试类`CommentServiceTest`,对保存和查询功能进行测试,并展示测试结果截图,验证功能的正确性。
368 2
|
运维 数据挖掘 索引
服务器数据恢复—Lustre分布式文件系统服务器数据恢复案例
5台节点服务器,每台节点服务器上有一组RAID5阵列。每组RAID5阵列上有6块硬盘(其中1块硬盘设置为热备盘,其他5块硬盘为数据盘)。上层系统环境为Lustre分布式文件系统。 机房天花板漏水导致这5台节点服务器进水,每台服务器都有至少2块硬盘出现故障。每台服务器中的RAID5阵列短时间内同时掉线2块或以上数量的硬盘,导致RAID崩溃,服务器中数据无法正常读取。
|
网络协议 Unix Linux
一个.NET开源、快速、低延迟的异步套接字服务器和客户端库
一个.NET开源、快速、低延迟的异步套接字服务器和客户端库
442 4
|
缓存 NoSQL Ubuntu
大数据-39 Redis 高并发分布式缓存 Ubuntu源码编译安装 云服务器 启动并测试 redis-server redis-cli
大数据-39 Redis 高并发分布式缓存 Ubuntu源码编译安装 云服务器 启动并测试 redis-server redis-cli
356 3
|
Web App开发 JavaScript 前端开发
使用Node.js和Express框架构建Web服务器
使用Node.js和Express框架构建Web服务器
|
Python
Flask学习笔记(二):基于Flask框架上传图片到服务器端并原名保存
关于如何使用Flask框架上传图片到服务器端并以其原名保存的教程。
781 1
|
分布式计算 Hadoop
Hadoop-27 ZooKeeper集群 集群配置启动 3台云服务器 myid集群 zoo.cfg多节点配置 分布式协调框架 Leader Follower Observer
Hadoop-27 ZooKeeper集群 集群配置启动 3台云服务器 myid集群 zoo.cfg多节点配置 分布式协调框架 Leader Follower Observer
428 1
|
Python
Flask学习笔记(三):基于Flask框架上传特征值(相关数据)到服务器端并保存为txt文件
这篇博客文章是关于如何使用Flask框架上传特征值数据到服务器端,并将其保存为txt文件的教程。
329 0
Flask学习笔记(三):基于Flask框架上传特征值(相关数据)到服务器端并保存为txt文件
|
存储 数据采集 分布式计算
Hadoop-17 Flume 介绍与环境配置 实机云服务器测试 分布式日志信息收集 海量数据 实时采集引擎 Source Channel Sink 串行复制负载均衡
Hadoop-17 Flume 介绍与环境配置 实机云服务器测试 分布式日志信息收集 海量数据 实时采集引擎 Source Channel Sink 串行复制负载均衡
414 1
|
存储 SQL 消息中间件
Hadoop-26 ZooKeeper集群 3台云服务器 基础概念简介与环境的配置使用 架构组成 分布式协调框架 Leader Follower Observer
Hadoop-26 ZooKeeper集群 3台云服务器 基础概念简介与环境的配置使用 架构组成 分布式协调框架 Leader Follower Observer
388 0

热门文章

最新文章

推荐镜像

更多