使用BookSleeve维护开放的Redis连接

使用BookSleeve维护开放的Redis连接,第1张

使用BookSleeve维护开放的Redis连接

由于我没有任何好的答案,所以我想出了这个解决方案(顺便说一句,感谢@Simon和@Alex的回答!)。

我想与所有社区分享作为参考。当然,任何更正将不胜感激。

using System;using System.Net.Sockets;using BookSleeve;namespace Redis{    public sealed class RedisConnectionGateway    {        private const string RedisConnectionFailed = "Redis connection failed.";        private RedisConnection _connection;        private static volatile RedisConnectionGateway _instance;        private static object syncLock = new object();        private static object syncConnectionLock = new object();        public static RedisConnectionGateway Current        { get {     if (_instance == null)     {         lock (syncLock)         {  if (_instance == null)  {      _instance = new RedisConnectionGateway();  }         }     }     return _instance; }        }        private RedisConnectionGateway()        { _connection = getNewConnection();        }        private static RedisConnection getNewConnection()        { return new RedisConnection("127.0.0.1" , syncTimeout: 5000, ioTimeout: 5000);        }        public RedisConnection GetConnection()        { 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)         {  throw new Exception(RedisConnectionFailed, ex);         }     }     if (_connection.State == RedisConnectionbase.ConnectionState.Shiny)     {         try         {  var openAsync = _connection.Open();  _connection.Wait(openAsync);         }         catch (SocketException ex)         {  throw new Exception(RedisConnectionFailed, ex);         }     }     return _connection; }        }    }}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4909811.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-12
下一篇2022-11-12

发表评论

登录后才能评论

评论列表(0条)

    保存