DBQueryBatchTask.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections.Generic;
  3. using MongoDB.Driver;
  4. namespace ETModel
  5. {
  6. [ObjectSystem]
  7. public class DbQueryBatchTaskSystem : AwakeSystem<DBQueryBatchTask, List<long>, string, ETTaskCompletionSource<List<ComponentWithId>>>
  8. {
  9. public override void Awake(DBQueryBatchTask self, List<long> idList, string collectionName, ETTaskCompletionSource<List<ComponentWithId>> tcs)
  10. {
  11. self.IdList = idList;
  12. self.CollectionName = collectionName;
  13. self.Tcs = tcs;
  14. }
  15. }
  16. public sealed class DBQueryBatchTask : DBTask
  17. {
  18. public string CollectionName { get; set; }
  19. public List<long> IdList { get; set; }
  20. public ETTaskCompletionSource<List<ComponentWithId>> Tcs { get; set; }
  21. public override async ETTask Run()
  22. {
  23. DBCacheComponent dbCacheComponent = Game.Scene.GetComponent<DBCacheComponent>();
  24. DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
  25. List<ComponentWithId> result = new List<ComponentWithId>();
  26. try
  27. {
  28. // 执行查询数据库任务
  29. foreach (long id in IdList)
  30. {
  31. ComponentWithId component = dbCacheComponent.GetFromCache(this.CollectionName, id);
  32. if (component == null)
  33. {
  34. IAsyncCursor<ComponentWithId> cursor = await dbComponent.GetCollection(this.CollectionName).FindAsync((s) => s.Id == id);
  35. component = await cursor.FirstOrDefaultAsync();
  36. }
  37. if (component == null)
  38. {
  39. continue;
  40. }
  41. result.Add(component);
  42. }
  43. this.Tcs.SetResult(result);
  44. }
  45. catch (Exception e)
  46. {
  47. this.Tcs.SetException(new Exception($"查询数据库异常! {this.CollectionName} {IdList.ListToString()}", e));
  48. }
  49. }
  50. }
  51. }