MessagePool.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using Vinno.IUS.Common.IO;
  7. using Vinno.IUS.Common.Log;
  8. namespace Vinno.IUS.Common.Network.Transfer
  9. {
  10. /// <summary>
  11. /// Message Pool
  12. /// </summary>
  13. public static class MessagePool
  14. {
  15. private static int _maximumMsgOfEachType = 10;
  16. private static bool _enabled;
  17. private static readonly object _getMessageLock = new Object();
  18. /// <summary>
  19. /// get Message pool is or not cached
  20. /// </summary>
  21. public static bool Enabled => _enabled;
  22. /// <summary>
  23. /// Maxinum of messages of each type
  24. /// </summary>
  25. public static int MaximumMessageOfEachType => _maximumMsgOfEachType;
  26. private static readonly ConcurrentDictionary<string, int?> MaxSpecialTypeMessageDictionary = new ConcurrentDictionary<string, int?>();
  27. private static readonly ConcurrentDictionary<Type, Stack<Message>> AvailableMessagePool = new ConcurrentDictionary<Type, Stack<Message>>();
  28. /// <summary>
  29. /// Get idle message from message pool
  30. /// if all message of type of T is working ,so get new message
  31. /// </summary>
  32. /// <typeparam name="T">Message</typeparam>
  33. /// <returns>T </returns>
  34. public static T GetMessage<T>() where T : Message
  35. {
  36. try
  37. {
  38. if (Enabled)
  39. {
  40. if (AvailableMessagePool.TryGetValue(typeof(T), out Stack<Message> messageStack))
  41. {
  42. lock (_getMessageLock)
  43. {
  44. if (messageStack.Count > 0)
  45. {
  46. var message = messageStack?.Pop();
  47. if (message != null)
  48. {
  49. return message as T;
  50. }
  51. }
  52. }
  53. }
  54. }
  55. }
  56. catch (Exception e)
  57. {
  58. throw new Exception($"{e}");
  59. }
  60. return NewMessage<T>();
  61. }
  62. private static T NewMessage<T>() where T : Message
  63. {
  64. var message = Activator.CreateInstance(typeof(T), new object[] { }) as Message;
  65. return message as T;
  66. }
  67. /// <summary>
  68. /// Release current message
  69. /// this message changed busy to idle
  70. /// </summary>
  71. /// <param name="message"></param>
  72. public static void Recover(Message message)
  73. {
  74. if (message == null)
  75. {
  76. return;
  77. }
  78. if (Enabled)
  79. {
  80. try
  81. {
  82. var messageType = message.GetType();
  83. AvailableMessagePool.AddOrUpdate(messageType, s =>
  84. {
  85. var stack = new Stack<Message>();
  86. stack.Push(RevertToMessage(message));
  87. return stack;
  88. }, (s, m) =>
  89. {
  90. var maximum = _maximumMsgOfEachType;
  91. MaxSpecialTypeMessageDictionary.TryGetValue(messageType.Name, out int? specialMaximum);
  92. if (specialMaximum != null)
  93. {
  94. maximum = specialMaximum.Value;
  95. }
  96. if (m.Count < maximum)
  97. {
  98. m.Push(RevertToMessage(message));
  99. }
  100. return m;
  101. });
  102. }
  103. catch (Exception e)
  104. {
  105. throw new InvalidOperationException($"MessagePool Recover,Error:{e}");
  106. }
  107. }
  108. }
  109. private static Message RevertToMessage(Message message)
  110. {
  111. var properties = message.GetType().GetProperties();
  112. foreach (var propertyInfo in properties)
  113. {
  114. if (propertyInfo.CanWrite)
  115. {
  116. if (propertyInfo.Name == nameof(message.Element) || propertyInfo.Name == nameof(message.Tag))
  117. {
  118. continue;
  119. }
  120. var defaultvalue = GetDefaultValue(propertyInfo.PropertyType);
  121. propertyInfo.SetValue(message, defaultvalue);
  122. }
  123. }
  124. return message;
  125. }
  126. private static object GetDefaultValue(Type type)
  127. {
  128. object value = null;
  129. switch (type.Name)
  130. {
  131. case nameof(String):
  132. value = string.Empty;
  133. break;
  134. case nameof(Enum):
  135. value = default(Enum);
  136. break;
  137. case nameof(Int32):
  138. value = 0;
  139. break;
  140. case nameof(Int16):
  141. value = 0;
  142. break;
  143. case nameof(Int64):
  144. value = 0;
  145. break;
  146. case nameof(Single):
  147. value = 0;
  148. break;
  149. case nameof(Double):
  150. value = 0;
  151. break;
  152. case nameof(Boolean):
  153. value = false;
  154. break;
  155. case nameof(DateTime):
  156. value = default(DateTime);
  157. break;
  158. case nameof(IBuffer):
  159. value = new ByteBuffer(new byte[0]);
  160. break;
  161. case "Byte[]":
  162. value = new byte[0];
  163. break;
  164. }
  165. return value;
  166. }
  167. public static void Initialize(IMessagePoolConfig config)
  168. {
  169. if (config !=null)
  170. {
  171. _enabled = config.Enabled;
  172. _maximumMsgOfEachType = config.MaximumNumberOfMessages;
  173. foreach (var key in config.CustomMessageCountDictionary)
  174. {
  175. MaxSpecialTypeMessageDictionary.GetOrAdd(key.Key, key.Value);
  176. }
  177. }
  178. }
  179. }
  180. /// <summary>
  181. /// interface message pool config
  182. /// </summary>
  183. public interface IMessagePoolConfig
  184. {
  185. /// <summary>
  186. /// MessagePool Enabled
  187. /// </summary>
  188. bool Enabled { get; }
  189. /// <summary>
  190. /// Maximum number of messages per type
  191. /// </summary>
  192. int MaximumNumberOfMessages { get; }
  193. /// <summary>
  194. /// custom message count,string:message name,int:maximum count of message
  195. /// </summary>
  196. Dictionary<string, int> CustomMessageCountDictionary { get; }
  197. }
  198. }