调整服务器逻辑

1、调整Entity.AddComponent方法添加的组件Id为父组件的Id。
2、增加了ISupportedSingleCollection和ISingleCollectionRoot接口.
3、增加了SingleCollection、用于把子组件保存到单独的数据库表的功能,配合ISupportedSingleCollection和ISingleCollectionRoot。
This commit is contained in:
ALEXTANG
2023-07-24 16:49:23 +08:00
parent 846dc4d4bc
commit f8056aef32
11 changed files with 224 additions and 29 deletions

View File

@@ -6,11 +6,13 @@ namespace TEngine.Core.DataBase;
public interface IDateBase
{
public static readonly CoroutineLockQueueType DataBaseLock = new CoroutineLockQueueType("DataBaseLock");
IDateBase Initialize(string connectionString, string dbName);
FTask<long> Count<T>(string collection = null) where T : Entity;
FTask<long> Count<T>(Expression<Func<T, bool>> filter, string collection = null) where T : Entity;
FTask<bool> Exist<T>(string collection = null) where T : Entity;
FTask<bool> Exist<T>(Expression<Func<T, bool>> filter, string collection = null) where T : Entity;
FTask<T> QueryNotLock<T>(long id, string collection = null) where T : Entity;
FTask<T> Query<T>(long id, string collection = null) where T : Entity;
FTask<(int count, List<T> dates)> QueryCountAndDatesByPage<T>(Expression<Func<T, bool>> filter, int pageIndex, int pageSize, string collection = null) where T : Entity;
FTask<(int count, List<T> dates)> QueryCountAndDatesByPage<T>(Expression<Func<T, bool>> filter, int pageIndex, int pageSize, string[] cols, string collection = null) where T : Entity;

View File

@@ -13,7 +13,6 @@ public sealed class MongoDataBase : IDateBase
private MongoClient _mongoClient;
private IMongoDatabase _mongoDatabase;
private readonly HashSet<string> _collections = new HashSet<string>();
private readonly CoroutineLockQueueType _mongoDataBaseLock = new CoroutineLockQueueType("MongoDataBaseLock");
public IDateBase Initialize(string connectionString, string dbName)
{
@@ -86,10 +85,16 @@ public sealed class MongoDataBase : IDateBase
#endregion
#region Query
public async FTask<T> QueryNotLock<T>(long id, string collection = null) where T : Entity
{
var cursor = await GetCollection<T>(collection).FindAsync(d => d.Id == id);
var v = await cursor.FirstOrDefaultAsync();
return v;
}
public async FTask<T> Query<T>(long id, string collection = null) where T : Entity
{
using (await _mongoDataBaseLock.Lock(id))
using (await IDateBase.DataBaseLock.Lock(id))
{
var cursor = await GetCollection<T>(collection).FindAsync(d => d.Id == id);
var v = await cursor.FirstOrDefaultAsync();
@@ -99,7 +104,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<(int count, List<T> dates)> QueryCountAndDatesByPage<T>(Expression<Func<T, bool>> filter, int pageIndex, int pageSize, string collection = null) where T : Entity
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
var count = await Count(filter);
var dates = await QueryByPage(filter, pageIndex, pageSize, collection);
@@ -109,7 +114,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<(int count, List<T> dates)> QueryCountAndDatesByPage<T>(Expression<Func<T, bool>> filter, int pageIndex, int pageSize, string[] cols, string collection = null) where T : Entity
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
var count = await Count(filter);
@@ -121,7 +126,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<List<T>> QueryByPage<T>(Expression<Func<T, bool>> filter, int pageIndex, int pageSize, string collection = null) where T : Entity
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
return await GetCollection<T>(collection).Find(filter).Skip((pageIndex - 1) * pageSize)
.Limit(pageSize)
@@ -131,7 +136,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<List<T>> QueryByPage<T>(Expression<Func<T, bool>> filter, int pageIndex, int pageSize, string[] cols, string collection = null) where T : Entity
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
var projection = Builders<T>.Projection.Include("");
@@ -147,7 +152,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<List<T>> QueryByPageOrderBy<T>(Expression<Func<T, bool>> filter, int pageIndex, int pageSize, Expression<Func<T, object>> orderByExpression, bool isAsc = true, string collection = null) where T : Entity
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
if (isAsc)
{
@@ -162,7 +167,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<T> First<T>(Expression<Func<T, bool>> filter, string collection = null) where T : Entity
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
var cursor = await GetCollection<T>(collection).FindAsync(filter);
@@ -172,7 +177,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<T> First<T>(string json, string[] cols, string collection = null) where T : Entity
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
var projection = Builders<T>.Projection.Include("");
@@ -193,7 +198,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<T> Last<T>(Expression<Func<T, bool>> filter, string collection = null) where T : Entity
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
var cursor = await GetCollection<T>(collection).FindAsync(filter);
@@ -205,7 +210,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<List<T>> QueryOrderBy<T>(Expression<Func<T, bool>> filter, Expression<Func<T, object>> orderByExpression, bool isAsc = true, string collection = null) where T : Entity
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
if (isAsc)
{
@@ -219,7 +224,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<List<T>> Query<T>(Expression<Func<T, bool>> filter, string collection = null) where T : Entity
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
var cursor = await GetCollection<T>(collection).FindAsync(filter);
var v = await cursor.ToListAsync();
@@ -229,7 +234,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask Query(long id, List<string> collectionNames, List<Entity> result)
{
using (await _mongoDataBaseLock.Lock(id))
using (await IDateBase.DataBaseLock.Lock(id))
{
if (collectionNames == null || collectionNames.Count == 0)
{
@@ -254,7 +259,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<List<T>> QueryJson<T>(string json, string collection = null) where T : Entity
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
FilterDefinition<T> filterDefinition = new JsonFilterDefinition<T>(json);
var cursor = await GetCollection<T>(collection).FindAsync(filterDefinition);
@@ -265,7 +270,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<List<T>> QueryJson<T>(string json, string[] cols, string collection = null) where T : Entity
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
var projection = Builders<T>.Projection.Include("");
@@ -286,7 +291,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<List<T>> QueryJson<T>(long taskId, string json, string collection = null) where T : Entity
{
using (await _mongoDataBaseLock.Lock(taskId))
using (await IDateBase.DataBaseLock.Lock(taskId))
{
FilterDefinition<T> filterDefinition = new JsonFilterDefinition<T>(json);
var cursor = await GetCollection<T>(collection).FindAsync(filterDefinition);
@@ -297,7 +302,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<List<T>> Query<T>(Expression<Func<T, bool>> filter, string[] cols, string collection = null) where T : class
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
var projection = Builders<T>.Projection.Include(cols[0]);
@@ -324,7 +329,7 @@ public sealed class MongoDataBase : IDateBase
var clone = MongoHelper.Instance.Clone(entity);
using (await _mongoDataBaseLock.Lock(clone.Id))
using (await IDateBase.DataBaseLock.Lock(clone.Id))
{
await GetCollection(collection ?? clone.GetType().Name).ReplaceOneAsync(
(IClientSessionHandle) transactionSession, d => d.Id == clone.Id, clone,
@@ -343,7 +348,7 @@ public sealed class MongoDataBase : IDateBase
var clone = MongoHelper.Instance.Clone(entity);
using (await _mongoDataBaseLock.Lock(clone.Id))
using (await IDateBase.DataBaseLock.Lock(clone.Id))
{
await GetCollection(collection ?? clone.GetType().Name).ReplaceOneAsync(d => d.Id == clone.Id, clone,
new ReplaceOptions {IsUpsert = true});
@@ -361,7 +366,7 @@ public sealed class MongoDataBase : IDateBase
var clone = MongoHelper.Instance.Clone(entity);
using (await _mongoDataBaseLock.Lock(clone.Id))
using (await IDateBase.DataBaseLock.Lock(clone.Id))
{
await GetCollection(collection ?? clone.GetType().Name).ReplaceOneAsync(d => d.Id == clone.Id, clone, new ReplaceOptions {IsUpsert = true});
}
@@ -377,7 +382,7 @@ public sealed class MongoDataBase : IDateBase
var clones = MongoHelper.Instance.Clone(entities);
using (await _mongoDataBaseLock.Lock(id))
using (await IDateBase.DataBaseLock.Lock(id))
{
foreach (Entity clone in clones)
{
@@ -405,7 +410,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask InsertBatch<T>(IEnumerable<T> list, string collection = null) where T : Entity, new()
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
await GetCollection<T>(collection ?? typeof(T).Name).InsertManyAsync(list);
}
@@ -413,7 +418,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask InsertBatch<T>(object transactionSession, IEnumerable<T> list, string collection = null) where T : Entity, new()
{
using (await _mongoDataBaseLock.Lock(RandomHelper.RandInt64()))
using (await IDateBase.DataBaseLock.Lock(RandomHelper.RandInt64()))
{
await GetCollection<T>(collection ?? typeof(T).Name).InsertManyAsync((IClientSessionHandle) transactionSession, list);
}
@@ -425,7 +430,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<long> Remove<T>(object transactionSession, long id, string collection = null) where T : Entity, new()
{
using (await _mongoDataBaseLock.Lock(id))
using (await IDateBase.DataBaseLock.Lock(id))
{
var result = await GetCollection<T>(collection).DeleteOneAsync((IClientSessionHandle) transactionSession, d => d.Id == id);
return result.DeletedCount;
@@ -434,7 +439,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<long> Remove<T>(long id, string collection = null) where T : Entity, new()
{
using (await _mongoDataBaseLock.Lock(id))
using (await IDateBase.DataBaseLock.Lock(id))
{
var result = await GetCollection<T>(collection).DeleteOneAsync(d => d.Id == id);
return result.DeletedCount;
@@ -443,7 +448,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<long> Remove<T>(long id, object transactionSession, Expression<Func<T, bool>> filter, string collection = null) where T : Entity, new()
{
using (await _mongoDataBaseLock.Lock(id))
using (await IDateBase.DataBaseLock.Lock(id))
{
var result = await GetCollection<T>(collection).DeleteManyAsync((IClientSessionHandle) transactionSession, filter);
return result.DeletedCount;
@@ -452,7 +457,7 @@ public sealed class MongoDataBase : IDateBase
public async FTask<long> Remove<T>(long id, Expression<Func<T, bool>> filter, string collection = null) where T : Entity, new()
{
using (await _mongoDataBaseLock.Lock(id))
using (await IDateBase.DataBaseLock.Lock(id))
{
var result = await GetCollection<T>(collection).DeleteManyAsync(filter);
return result.DeletedCount;

View File

@@ -321,7 +321,7 @@ namespace TEngine
public T AddComponent<T>() where T : Entity, new()
{
var entity = Create<T>(Scene.RouteId, false);
var entity = Create<T>(Id, Scene.RouteId, false);
AddComponent(entity);
EntitiesSystem.Instance.Awake(entity);
EntitiesSystem.Instance.StartUpdate(entity);
@@ -367,6 +367,12 @@ namespace TEngine
}
else
{
#if TENGINE_NET
if (component is ISupportedSingleCollection && component.Id != Id)
{
Log.Error($"component type :{component.GetType().FullName} for implementing ISupportedSingleCollection, it is required that the Id must be the same as the parent");
}
#endif
if (_tree == null)
{
_tree = DictionaryPool<Type, Entity>.Create();
@@ -405,6 +411,8 @@ namespace TEngine
#region GetComponent
public DictionaryPool<Type, Entity> GetTree => _tree;
public T GetComponent<T>() where T : Entity, new()
{
return GetComponent(typeof(T)) as T;

View File

@@ -0,0 +1,8 @@
#if TENGINE_NET
namespace TEngine;
/// <summary>
/// Entity保存到数据库的时候会根据子组件设置分离存储特性分表存储在不同的集合表中
/// </summary>
public interface ISingleCollectionRoot { }
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3dfa22a9da7a76b41bf6511e45b22b53
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,23 @@
#if TENGINE_NET
namespace TEngine;
/// <summary>
/// Entity是单一集合、保存到数据库的时候不会跟随父组件保存在一个集合里、会单独保存在一个集合里
/// 需要配合SingleCollectionAttribute一起使用、如在Entity类头部定义SingleCollectionAttribute(typeOf(Unit))
/// SingleCollectionAttribute用来定义这个Entity是属于哪个Entity的子集
/// </summary>
public interface ISupportedSingleCollection { }
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class SingleCollectionAttribute : Attribute
{
public readonly Type RootType;
public readonly string CollectionName;
public SingleCollectionAttribute(Type rootType, string collectionName)
{
RootType = rootType;
CollectionName = collectionName;
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d9654cddb77221d4eaa991df735b12c2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -16,7 +16,7 @@ namespace TEngine.Core.Network
public uint ChannelId { get; private set; }
public long LastReceiveTime { get; private set; }
public ANetworkMessageScheduler NetworkMessageScheduler { get; private set;}
private static readonly Dictionary<long, Session> Sessions = new ();
public static readonly Dictionary<long, Session> Sessions = new ();
public readonly Dictionary<long, FTask<IResponse>> RequestCallback = new();
public static void Create(ANetworkMessageScheduler networkMessageScheduler, ANetworkChannel channel, NetworkTarget networkTarget)

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e35142e7e2685824486acc859cda6f0d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,108 @@
#if TENGINE_NET
using TEngine.Core.DataBase;
using TEngine.DataStructure;
// ReSharper disable SuspiciousTypeConversion.Global
namespace TEngine.Core;
public class SingleCollection : Singleton<SingleCollection>
{
private readonly OneToManyHashSet<Type, string> _collection = new OneToManyHashSet<Type, string>();
private readonly OneToManyList<int, SingleCollectionInfo> _assemblyCollections = new OneToManyList<int, SingleCollectionInfo>();
private sealed class SingleCollectionInfo
{
public readonly Type RootType;
public readonly string CollectionName;
public SingleCollectionInfo(Type rootType, string collectionName)
{
RootType = rootType;
CollectionName = collectionName;
}
}
protected override void OnLoad(int assemblyName)
{
foreach (var type in AssemblyManager.ForEach(assemblyName, typeof(ISupportedSingleCollection)))
{
var customAttributes = type.GetCustomAttributes(typeof(SingleCollectionAttribute), false);
if (customAttributes.Length == 0)
{
Log.Error($"type {type.FullName} Implemented the interface of ISingleCollection, requiring the implementation of SingleCollectionAttribute");
continue;
}
var singleCollectionAttribute = (SingleCollectionAttribute)customAttributes[0];
var rootType = singleCollectionAttribute.RootType;
var collectionName = singleCollectionAttribute.CollectionName;
_collection.Add(rootType, collectionName);
_assemblyCollections.Add(assemblyName, new SingleCollectionInfo(rootType, collectionName));
}
}
protected override void OnUnLoad(int assemblyName)
{
if (!_assemblyCollections.TryGetValue(assemblyName, out var types))
{
return;
}
foreach (var singleCollectionInfo in types)
{
_collection.RemoveValue(singleCollectionInfo.RootType, singleCollectionInfo.CollectionName);
}
_assemblyCollections.RemoveByKey(assemblyName);
}
public async FTask GetCollections(Entity entity)
{
if (entity is not ISingleCollectionRoot)
{
return;
}
if (!_collection.TryGetValue(entity.GetType(), out var collections))
{
return;
}
var scene = entity.Scene;
var worldDateBase = scene.World.DateBase;
using (await IDateBase.DataBaseLock.Lock(entity.Id))
{
foreach (var collectionName in collections)
{
var singleCollection = await worldDateBase.QueryNotLock<Entity>(entity.Id, collectionName);
singleCollection.Deserialize(scene);
entity.AddComponent(singleCollection);
}
}
}
public async FTask SaveCollections(Entity entity)
{
if (entity is not ISingleCollectionRoot)
{
return;
}
using var collections = ListPool<Entity>.Create();
foreach (var (_, treeEntity) in entity.GetTree)
{
if (treeEntity is not ISupportedSingleCollection)
{
continue;
}
collections.Add(treeEntity);
}
await entity.Scene.World.DateBase.Save(entity.Id, collections);
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 533ab9c301a66054cbcd8cc8ec8b1bc0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: