using System; using System.Linq; using BookSleeve; using System.Net.Sockets; using Sony.Filtr.ErrorLogging; namespace Sony.Filtr.PersistentCaching { //Code for maintaining a Redis-Connection and handle failures. public sealed class PersistentCachingManager { private RedisConnection _connection; private static volatile PersistentCachingManager _instance; private static readonly object syncLock = new object(); private static readonly object syncConnectionLock = new object(); //public static PersistentCachingManager Instance //{ // get // { // if (_instance == null) // { // lock (syncLock) // { // if (_instance == null) // { // _instance = new PersistentCachingManager(); // } // } // } // return _instance; // } //} private PersistentCachingManager() { _connection = GetNewConnection(); } private static RedisConnection GetNewConnection() { return new RedisConnection(System.Configuration.ConfigurationManager.AppSettings["Redis-HostName"], syncTimeout: 5000, ioTimeout: 1000); } public RedisConnection Connection { get { lock (syncConnectionLock) { if (_connection == null) _connection = GetNewConnection(); if (_connection.State == RedisConnectionBase.ConnectionState.Opening) return _connection; if (_connection.State == RedisConnectionBase.ConnectionState.Closing || _connection.State == RedisConnectionBase.ConnectionState.Closed) { try { _connection = GetNewConnection(); } catch (Exception ex) { ErrorLoggingManager.Instance.LogError(ex); return null; } } if (_connection.State == RedisConnectionBase.ConnectionState.New) { try { var openAsync = _connection.Open(); _connection.Wait(openAsync); } catch (SocketException ex) { ErrorLoggingManager.Instance.LogError(ex); return null; } } return _connection; } } } } }