JsonRpcClientPool.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System.Collections.Concurrent;
  2. using JsonRpcLite.Rpc;
  3. using JsonRpcLite.InProcess;
  4. using JsonRpcLite.Network;
  5. using WingServerCommon.Log;
  6. namespace WingServerCommon.Service
  7. {
  8. public class JsonRpcClientPool
  9. {
  10. private readonly ConcurrentDictionary<string, JsonRpcClient> _jsonRpcClients = new ConcurrentDictionary<string, JsonRpcClient>();
  11. private readonly JsonRpcClient _inProcessRpcClient;
  12. public JsonRpcClientPool(JsonRpcInProcessEngine inProcessEngine)
  13. {
  14. _inProcessRpcClient = new JsonRpcClient();
  15. _inProcessRpcClient.UseEngine(inProcessEngine);
  16. }
  17. /// <summary>
  18. /// Initialize Json Rpc Client pool with specified service info
  19. /// </summary>
  20. /// <param name="serviceInfos"></param>
  21. public void Initialize(RemoteServiceInfo[] serviceInfos)
  22. {
  23. foreach(var info in serviceInfos)
  24. {
  25. Add(info);
  26. }
  27. }
  28. /// <summary>
  29. /// Add a rpc client with specified service info
  30. /// </summary>
  31. /// <param name="serviceInfo">Service info</param>
  32. public void Add(RemoteServiceInfo serviceInfo)
  33. {
  34. var rpcClient = new JsonRpcClient();
  35. var clientEngine = new JsonRpcHttpClientEngine(serviceInfo.Url);
  36. rpcClient.UseEngine(clientEngine);
  37. if (_jsonRpcClients.TryAdd(serviceInfo.ServiceName, rpcClient))
  38. {
  39. Logger.WriteLineInfo($"Create JsonRpcClient {serviceInfo.ServiceName} with url:{serviceInfo.Url}");
  40. }
  41. }
  42. /// <summary>
  43. /// remove a rpc client with specified service info
  44. /// </summary>
  45. /// <param name="serviceInfo"></param>
  46. public void Remove(string serviceName)
  47. {
  48. if(_jsonRpcClients.TryRemove(serviceName, out var client))
  49. {
  50. client?.Dispose();
  51. }
  52. }
  53. /// <summary>
  54. /// Get json prc client with specified service type
  55. /// </summary>
  56. /// <typeparam name="T">The type that implemented interface IJsonRpcService</typeparam>
  57. /// <returns></returns>
  58. public JsonRpcClient GetJsonRpcClient<T>()
  59. {
  60. var type = typeof(T);
  61. var serviceName = type.Name;
  62. if (_jsonRpcClients.TryGetValue(serviceName, out var client) && client !=null)
  63. {
  64. return client;
  65. }
  66. return _inProcessRpcClient;
  67. }
  68. /// <summary>
  69. /// Dispose
  70. /// </summary>
  71. public void Dispose()
  72. {
  73. _inProcessRpcClient.Dispose();
  74. var clientKeys = _jsonRpcClients.Keys.ToList();
  75. foreach(var key in clientKeys)
  76. {
  77. if(_jsonRpcClients.TryRemove(key, out var client))
  78. {
  79. client?.Dispose();
  80. }
  81. }
  82. }
  83. }
  84. }