ActorMessageDispatherComponent.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. namespace Model
  5. {
  6. [ObjectSystem]
  7. public class ActorMessageDispatherComponentStartSystem : AwakeSystem<ActorMessageDispatherComponent>
  8. {
  9. public override void Awake(ActorMessageDispatherComponent self)
  10. {
  11. self.Awake();
  12. }
  13. }
  14. [ObjectSystem]
  15. public class ActorMessageDispatherComponentLoadSystem : LoadSystem<ActorMessageDispatherComponent>
  16. {
  17. public override void Load(ActorMessageDispatherComponent self)
  18. {
  19. self.Load();
  20. }
  21. }
  22. /// <summary>
  23. /// Actor消息分发组件
  24. /// </summary>
  25. public class ActorMessageDispatherComponent : Component
  26. {
  27. private Dictionary<Type, IMActorHandler> handlers;
  28. public void Awake()
  29. {
  30. this.Load();
  31. }
  32. public void Load()
  33. {
  34. AppType appType = this.Entity.GetComponent<StartConfigComponent>().StartConfig.AppType;
  35. Log.Info("apptype: " + appType);
  36. this.handlers = new Dictionary<Type, IMActorHandler>();
  37. Type[] types = DllHelper.GetMonoTypes();
  38. foreach (Type type in types)
  39. {
  40. object[] attrs = type.GetCustomAttributes(typeof(ActorMessageHandlerAttribute), false);
  41. if (attrs.Length == 0)
  42. {
  43. continue;
  44. }
  45. ActorMessageHandlerAttribute messageHandlerAttribute = (ActorMessageHandlerAttribute)attrs[0];
  46. if (!messageHandlerAttribute.Type.Is(appType))
  47. {
  48. continue;
  49. }
  50. object obj = Activator.CreateInstance(type);
  51. IMActorHandler imHandler = obj as IMActorHandler;
  52. if (imHandler == null)
  53. {
  54. throw new Exception($"message handler not inherit AMEvent or AMRpcEvent abstract class: {obj.GetType().FullName}");
  55. }
  56. Type messageType = imHandler.GetMessageType();
  57. handlers.Add(messageType, imHandler);
  58. }
  59. }
  60. public IMActorHandler GetActorHandler(Type type)
  61. {
  62. this.handlers.TryGetValue(type, out IMActorHandler actorHandler);
  63. return actorHandler;
  64. }
  65. public async Task Handle(Session session, Entity entity, uint rpcId, ActorRequest message)
  66. {
  67. if (!this.handlers.TryGetValue(message.AMessage.GetType(), out IMActorHandler handler))
  68. {
  69. throw new Exception($"not found message handler: {MongoHelper.ToJson(message)}");
  70. }
  71. await handler.Handle(session, entity, rpcId, message);
  72. }
  73. public override void Dispose()
  74. {
  75. if (this.IsDisposed)
  76. {
  77. return;
  78. }
  79. base.Dispose();
  80. }
  81. }
  82. }