1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- using System.Collections.Concurrent;
- using JsonRpcLite.Rpc;
- using JsonRpcLite.InProcess;
- using JsonRpcLite.Network;
- using WingServerCommon.Log;
- namespace WingServerCommon.Service
- {
- public class JsonRpcClientPool
- {
- private readonly ConcurrentDictionary<string, JsonRpcClient> _jsonRpcClients = new ConcurrentDictionary<string, JsonRpcClient>();
- private readonly JsonRpcClient _inProcessRpcClient;
-
- public JsonRpcClientPool(JsonRpcInProcessEngine inProcessEngine)
- {
- _inProcessRpcClient = new JsonRpcClient();
- _inProcessRpcClient.UseEngine(inProcessEngine);
- }
- /// <summary>
- /// Initialize Json Rpc Client pool with specified service info
- /// </summary>
- /// <param name="serviceInfos"></param>
- public void Initialize(RemoteServiceInfo[] serviceInfos)
- {
- foreach(var info in serviceInfos)
- {
- Add(info);
- }
- }
-
- /// <summary>
- /// Add a rpc client with specified service info
- /// </summary>
- /// <param name="serviceInfo">Service info</param>
- public void Add(RemoteServiceInfo serviceInfo)
- {
- var rpcClient = new JsonRpcClient();
- var clientEngine = new JsonRpcHttpClientEngine(serviceInfo.Url);
- rpcClient.UseEngine(clientEngine);
- if (_jsonRpcClients.TryAdd(serviceInfo.ServiceName, rpcClient))
- {
- Logger.WriteLineInfo($"Create JsonRpcClient {serviceInfo.ServiceName} with url:{serviceInfo.Url}");
- }
- }
- /// <summary>
- /// remove a rpc client with specified service info
- /// </summary>
- /// <param name="serviceInfo"></param>
- public void Remove(string serviceName)
- {
- if(_jsonRpcClients.TryRemove(serviceName, out var client))
- {
- client?.Dispose();
- }
- }
- /// <summary>
- /// Get json prc client with specified service type
- /// </summary>
- /// <typeparam name="T">The type that implemented interface IJsonRpcService</typeparam>
- /// <returns></returns>
- public JsonRpcClient GetJsonRpcClient<T>()
- {
- var type = typeof(T);
- var serviceName = type.Name;
- if (_jsonRpcClients.TryGetValue(serviceName, out var client) && client !=null)
- {
- return client;
- }
- return _inProcessRpcClient;
- }
- /// <summary>
- /// Dispose
- /// </summary>
- public void Dispose()
- {
- _inProcessRpcClient.Dispose();
- var clientKeys = _jsonRpcClients.Keys.ToList();
- foreach(var key in clientKeys)
- {
- if(_jsonRpcClients.TryRemove(key, out var client))
- {
- client?.Dispose();
- }
- }
- }
- }
- }
|