using LJLib.Net.SPI.Client; using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace LJLib.Client { public sealed class LJClientPool : ILJClient { private const int DEFAULT_RETRY_COUNT = 1; private LJClientCreator _creator; private ILJClient[] _clients; private bool[] _client_states; private object _syncRoot = new object(); public LJClientPool(LJClientCreator creator, int size) { _creator = creator; _clients = new ILJClient[size]; _client_states = new bool[size]; for (int i = 0; i < size; i++) { _clients[i] = null; _client_states[i] = false; } } public string DoExcute(string apiName, string requestJSON) { int i; do { lock (_syncRoot) { for (i = 0; i < _client_states.Length; i++) { if (!_client_states[i]) { _client_states[i] = true; break; } } } if (i >= _client_states.Length) { Thread.Sleep(100); } } while (i >= _client_states.Length); try { int retry = 0; string rslt = null; while (retry <= DEFAULT_RETRY_COUNT) { try { if (_clients[i] == null) { _clients[i] = _creator.newClient(); } rslt = _clients[i].DoExcute(apiName, requestJSON); break; } catch (Exception e) { Trace.Write(e.ToString()); if (_clients[i] != null) { _clients[i].Dispose(); _clients[i] = null; } ++retry; if (retry > DEFAULT_RETRY_COUNT) { throw e;//大于重试次数时异常重抛 } } } return rslt; } catch (Exception ex) { Trace.Write(ex.ToString()); return ex.ToString(); } finally { _client_states[i] = false; } } public void Beat() { for (int i = 0; i < _client_states.Length; i++) { lock (_syncRoot) { if (_client_states[i]) { continue; } _client_states[i] = true; } try { //空实例无须心跳 if (_clients[i] != null) { _clients[i].Beat(); } } catch (Exception e) { _clients[i].Dispose(); _clients[i] = null; Trace.Write("连接池请求异常" + e.ToString()); } finally { _client_states[i] = false; } } } public void Dispose() { for (int i = 0; i < _clients.Length; i++) { if (_clients[i] != null) { _clients[i].Dispose(); _clients[i] = null; } } } } }