DBQueryTask.cs 1.4 KB

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