DBQueryTask.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using MongoDB.Driver;
  3. namespace ETModel
  4. {
  5. [ObjectSystem]
  6. public class DBQueryTaskSystem : AwakeSystem<DBQueryTask, string, ETTaskCompletionSource<ComponentWithId>>
  7. {
  8. public override void Awake(DBQueryTask self, string collectionName, ETTaskCompletionSource<ComponentWithId> tcs)
  9. {
  10. self.CollectionName = collectionName;
  11. self.Tcs = tcs;
  12. }
  13. }
  14. public sealed class DBQueryTask : DBTask
  15. {
  16. public string CollectionName { get; set; }
  17. public ETTaskCompletionSource<ComponentWithId> Tcs { get; set; }
  18. public override async ETTask Run()
  19. {
  20. DBCacheComponent dbCacheComponent = Game.Scene.GetComponent<DBCacheComponent>();
  21. DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
  22. // 执行查询前先看看cache中是否已经存在
  23. ComponentWithId component = dbCacheComponent.GetFromCache(this.CollectionName, this.Id);
  24. if (component != null)
  25. {
  26. this.Tcs.SetResult(component);
  27. return;
  28. }
  29. try
  30. {
  31. // 执行查询数据库任务
  32. IAsyncCursor<ComponentWithId> cursor = await dbComponent.GetCollection(this.CollectionName).FindAsync((s) => s.Id == this.Id);
  33. component = await cursor.FirstOrDefaultAsync();
  34. this.Tcs.SetResult(component);
  35. }
  36. catch (Exception e)
  37. {
  38. this.Tcs.SetException(new Exception($"查询数据库异常! {CollectionName} {Id}", e));
  39. }
  40. }
  41. }
  42. }