using StackExchange.Redis; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SMP.Common.WebRegion { public static class RedisUnit { public static async Task DeleteScanKey(this IDatabase db, IBatch batch, string pattern) { var redisResult = await db.ScriptEvaluateAsync(LuaScript.Prepare( //Redis的keys模糊查询: " local res = redis.call(\'KEYS\', @keypattern) " + " return res "), new { @keypattern = pattern }); if (!redisResult.IsNull) { if (batch != null) batch.KeyDeleteAsync((RedisKey[])redisResult); else return db.KeyDelete((RedisKey[])redisResult); return 0; } else { return 0; } } } public class RedisHelper : IDisposable { //连接字符串 private string _connectionString; //实例名称 private string _instanceName; //密码 private string _password; //默认数据库 private int _defaultDB; private ConcurrentDictionary _connections; public RedisHelper(string connectionString, string instanceName, string password, int defaultDB = 0) { _connectionString = connectionString; _instanceName = instanceName; _password = password; _defaultDB = defaultDB; _connections = new ConcurrentDictionary(); } /// /// 获取ConnectionMultiplexer /// /// private ConnectionMultiplexer GetConnect() { return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(new ConfigurationOptions { AbortOnConnectFail = false, Password = _password, EndPoints = { _connectionString } })); } /// /// 获取数据库 /// /// /// 默认为0:优先代码的db配置,其次config中的配置 /// public IDatabase GetDatabase() { return GetConnect().GetDatabase(_defaultDB); } public IServer GetServer(string configName = null, int endPointsIndex = 0) { if (string.IsNullOrEmpty(configName)) configName = _instanceName; var endpoint = _connections[configName].GetEndPoints()[0]; return GetConnect().GetServer(endpoint); } 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(); } } } } }