ActorMessageDispatherComponent.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 Dictionary<Type, IMActorHandler> handlers;
  24. public void Start()
  25. {
  26. this.Load();
  27. }
  28. public void Load()
  29. {
  30. AppType appType = this.GetComponent<StartConfigComponent>().StartConfig.AppType;
  31. Log.Info("apptype: " + appType);
  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(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 Handle(Session session, Entity entity, ActorRequest message)
  62. {
  63. if (!this.handlers.TryGetValue(message.AMessage.GetType(), out IMActorHandler handler))
  64. {
  65. throw new Exception($"not found message handler: {MongoHelper.ToJson(message)}");
  66. }
  67. await handler.Handle(session, entity, message);
  68. }
  69. public override void Dispose()
  70. {
  71. if (this.Id == 0)
  72. {
  73. return;
  74. }
  75. base.Dispose();
  76. }
  77. }
  78. }