LockComponentSystem.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.Net;
  3. using ETModel;
  4. namespace ETHotfix
  5. {
  6. [ObjectSystem]
  7. public class LockComponentAwakeSystem : AwakeSystem<LockComponent, IPEndPoint>
  8. {
  9. public override void Awake(LockComponent self, IPEndPoint a)
  10. {
  11. self.Awake(a);
  12. }
  13. }
  14. /// <summary>
  15. /// 分布式锁组件,Unit对象可能在不同进程上有镜像,访问该对象的时候需要对他加锁
  16. /// </summary>
  17. public static class LockComponentEx
  18. {
  19. public static void Awake(this LockComponent self, IPEndPoint addr)
  20. {
  21. self.address = addr;
  22. }
  23. public static async ETTask Lock(this LockComponent self)
  24. {
  25. ++self.lockCount;
  26. if (self.status == LockStatus.Locked)
  27. {
  28. return;
  29. }
  30. if (self.status == LockStatus.LockRequesting)
  31. {
  32. await self.WaitLock();
  33. return;
  34. }
  35. self.status = LockStatus.LockRequesting;
  36. // 真身直接本地请求锁,镜像需要调用Rpc获取锁
  37. MasterComponent masterComponent = self.Entity.GetComponent<MasterComponent>();
  38. if (masterComponent != null)
  39. {
  40. await masterComponent.Lock(self.address);
  41. }
  42. else
  43. {
  44. self.RequestLock().NoAwait();
  45. await self.WaitLock();
  46. }
  47. }
  48. private static ETTask WaitLock(this LockComponent self)
  49. {
  50. if (self.status == LockStatus.Locked)
  51. {
  52. return ETTask.FromResult(true);
  53. }
  54. ETTaskCompletionSource tcs = new ETTaskCompletionSource();
  55. self.queue.Enqueue(tcs);
  56. return tcs.Task;
  57. }
  58. private static async ETVoid RequestLock(this LockComponent self)
  59. {
  60. try
  61. {
  62. Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.address);
  63. string serverAddress = StartConfigComponent.Instance.StartConfig.ServerIP;
  64. G2G_LockRequest request = new G2G_LockRequest { Id = self.Entity.Id, Address = serverAddress };
  65. await session.Call(request);
  66. self.status = LockStatus.Locked;
  67. foreach (ETTaskCompletionSource taskCompletionSource in self.queue)
  68. {
  69. taskCompletionSource.SetResult();
  70. }
  71. self.queue.Clear();
  72. }
  73. catch (Exception e)
  74. {
  75. Log.Error($"获取锁失败: {self.address} {self.Entity.Id} {e}");
  76. }
  77. }
  78. public static async ETTask Release(this LockComponent self)
  79. {
  80. --self.lockCount;
  81. if (self.lockCount != 0)
  82. {
  83. return;
  84. }
  85. self.status = LockStatus.LockedNot;
  86. Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.address);
  87. G2G_LockReleaseRequest request = new G2G_LockReleaseRequest();
  88. await session.Call(request);
  89. }
  90. }
  91. }