分布式服务器框架之Server.Core库中实现YFUniqueEntity、YFUniqueIDBase 管理MongoDB 自定义Id的自增

        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<YFUniqueEntity> options = new FindOneAndUpdateOptions<YFUniqueEntity>();

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

        protected abstract string DatabaseName
        {
            get;
        }

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


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

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

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

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

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

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

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

        #endregion


    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值