ActorMessageDispatherComponent.cs 2.3 KB

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