using StackExchange.Redis; using System; using System.Collections.Concurrent; namespace RedisDemo { public class RedisHelper : IDisposable { //连接字符串 private string _connectionString; //实例名称 private string _instanceName; //默认数据库 private int _defaultDB; private ConcurrentDictionary _connections; public RedisHelper(string connectionString, string instanceName, int defaultDB = 0) { _connectionString = connectionString; _instanceName = instanceName; _defaultDB = defaultDB; _connections = new ConcurrentDictionary(); } /// /// 获取ConnectionMultiplexer /// /// private ConnectionMultiplexer GetConnect() { return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(_connectionString)); } /// /// 获取数据库 /// /// /// 默认为0:优先代码的db配置,其次config中的配置 /// public IDatabase GetDatabase() { var connectStr = _connectionString; var conmper = ConnectionMultiplexer.Connect(connectStr); var database = conmper.GetDatabase(0); return database; //return GetConnect().GetDatabase(_defaultDB); } public IServer GetServer(string configName = null, int endPointsIndex = 0) { var confOption = ConfigurationOptions.Parse(_connectionString); return GetConnect().GetServer(confOption.EndPoints[endPointsIndex]); } public ISubscriber GetSubscriber(string configName = null) { return GetConnect().GetSubscriber(); } public void Dispose() { if (_connections != null && _connections.Count > 0) { foreach (var item in _connections.Values) { item.Close(); } } } } }