123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140 |
- 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;
- }
- }
- }
- }
- }
|