123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- 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<long> 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<string, ConnectionMultiplexer> _connections;
- public RedisHelper(string connectionString, string instanceName, string password, int defaultDB = 0)
- {
- _connectionString = connectionString;
- _instanceName = instanceName;
- _password = password;
- _defaultDB = defaultDB;
- _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
- }
- /// <summary>
- /// 获取ConnectionMultiplexer
- /// </summary>
- /// <returns></returns>
- private ConnectionMultiplexer GetConnect()
- {
- return _connections.GetOrAdd(_instanceName, p =>
- ConnectionMultiplexer.Connect(new ConfigurationOptions
- {
- AbortOnConnectFail = false,
- Password = _password,
- EndPoints = {
- _connectionString
- }
- }));
- }
- /// <summary>
- /// 获取数据库
- /// </summary>
- /// <param name="configName"></param>
- /// <param name="db">默认为0:优先代码的db配置,其次config中的配置</param>
- /// <returns></returns>
- 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();
- }
- }
- }
- }
- }
|