您当前的位置: 首页 >  dba

天才小熊猫oo

暂无认证

  • 0浏览

    0关注

    37博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Server.Core库中实现YFUniqueEntity、YFUniqueIDBase 管理MongoDB 自定义Id的自增

天才小熊猫oo 发布时间:2022-10-12 22:15:23 ,浏览量:0

        YFUniqueEntity是数据库中的结构,GetUniqueID函数中会根据Type和自增步长去数据库中寻找该类型的当前ID是多少,然后会用当前的Id去加上步长,把更新后的新ID插入到MongoDB中记录着ID的那张表里。

       

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;

namespace Servers.Core
{
    //唯一实体
    public class YFUniqueEntity
    {
        //Id
        public ObjectId Id;

        //类型
        public ushort Type = 0;

        //当前Id
        public long CurrId = 0;
    }

    //唯一Id管理器
    public abstract class YFUniqueIDBase
    {
        //??这个是干啥的
        private FindOneAndUpdateOptions options = new FindOneAndUpdateOptions();

        #region 子类需要实现的属性
        protected abstract MongoClient Client
        {
            get;
        }

        protected abstract string DatabaseName
        {
            get;
        }

        //集合名称
        protected abstract string CollectionName
        {
            get;
        }
        #endregion


        #region 获取文档集合 GetCollection
        private IMongoCollection m_Collection = null;

        //获取文档集合
        public IMongoCollection GetCollection()
        {
            if (null == m_Collection)
            {
                IMongoDatabase database = Client.GetDatabase(DatabaseName);
                m_Collection = database.GetCollection(CollectionName);
            }
            return m_Collection;
        }

        //获取唯一Id
        public long GetUniqueID(int type, int seq = 1)
        {
            IMongoCollection collection = GetCollection();

            YFUniqueEntity entity = collection.FindOneAndUpdate(
                Builders.Filter.Eq(t => t.Type, type),
                Builders.Update.Inc(t => t.CurrId, seq),
                options
                );

            return entity == null ? seq : entity.CurrId + seq;
        }

        //异步获取唯一Id
        public async Task GetUniqueIDAsync(int type, int seq = 1)
        {
            IMongoCollection collection = GetCollection();
            YFUniqueEntity entity = await m_Collection.FindOneAndUpdateAsync(
                Builders.Filter.Eq(t => t.Type, type),
                Builders.Update.Inc(t => t.CurrId, seq),
                options);

            return entity == null ? seq : entity.CurrId + seq;
        }

        #endregion


    }
}

关注
打赏
1665545649
查看更多评论
立即登录/注册

微信扫码登录

0.0391s