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 } }