ActorMessageDispatherComponent.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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>, IStart, ILoad
  8. {
  9. public void Start()
  10. {
  11. this.Get().Start();
  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 Start()
  26. {
  27. StartConfig startConfig = this.GetComponent<StartConfigComponent>().StartConfig;
  28. this.AppType = startConfig.AppType;
  29. this.Load();
  30. }
  31. public void Load()
  32. {
  33. this.handlers = new Dictionary<Type, IMActorHandler>();
  34. Type[] types = DllHelper.GetMonoTypes();
  35. foreach (Type type in types)
  36. {
  37. object[] attrs = type.GetCustomAttributes(typeof(ActorMessageHandlerAttribute), false);
  38. if (attrs.Length == 0)
  39. {
  40. continue;
  41. }
  42. ActorMessageHandlerAttribute messageHandlerAttribute = (ActorMessageHandlerAttribute)attrs[0];
  43. if (!messageHandlerAttribute.Type.Is(this.AppType))
  44. {
  45. continue;
  46. }
  47. object obj = Activator.CreateInstance(type);
  48. IMActorHandler imHandler = obj as IMActorHandler;
  49. if (imHandler == null)
  50. {
  51. throw new Exception($"message handler not inherit AMEvent or AMRpcEvent abstract class: {obj.GetType().FullName}");
  52. }
  53. Type messageType = imHandler.GetMessageType();
  54. handlers.Add(messageType, imHandler);
  55. }
  56. }
  57. public IMActorHandler GetActorHandler(Type type)
  58. {
  59. this.handlers.TryGetValue(type, out IMActorHandler actorHandler);
  60. return actorHandler;
  61. }
  62. public async Task<bool> Handle(Session session, Entity entity, ActorRequest message)
  63. {
  64. if (!this.handlers.TryGetValue(message.AMessage.GetType(), out IMActorHandler handler))
  65. {
  66. Log.Error($"not found message handler: {message.GetType().FullName}");
  67. return false;
  68. }
  69. return await handler.Handle(session, entity, message);
  70. }
  71. public override void Dispose()
  72. {
  73. if (this.Id == 0)
  74. {
  75. return;
  76. }
  77. base.Dispose();
  78. }
  79. }
  80. }