C# StackExchange.Redis RedisHelper 工具类
StackExchange.Redis RedisHelper 工具类
Install-Package StackExchange.Redis
using Microsoft.Extensions.Configuration;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using NLog;
namespace VipSoft.DevOps
{
public class RedisHelper
{
private readonly Logger logger = LogManager.GetCurrentClassLogger(); //初始化日志类
private static readonly object Locker = new object();
private static IConnectionMultiplexer _connection;
private IDatabase _db;
public string ConnectionString { get; set; }
public static IConfigurationRoot Configuration
{
get
{
if (File.Exists(AppContext.BaseDirectory + "appsettings.json"))
{
return new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
}
throw new Exception("appsettings.json 文件不存在");
}
}
private RedisHelper(int dbindex)
{
if (_connection == null)
{
lock (Locker)
{
if (_connection == null || !_connection.IsConnected)
{
if (_connection != null)
{
//如果 redis !=null 且没有连接,先释放
_connection.Dispose();
}
var _host = Configuration.GetValue<string>($"Cluster:Redis:host");
var _port = Configuration.GetValue<string>($"Cluster:Redis:port");
var _pwd = Configuration.GetValue<string>($"Cluster:Redis:password");
// Redis 连接配置
ConnectionString = $"{_host}:{_port}"; // 修改为你的 Redis 服务器地址和端口
var options = ConfigurationOptions.Parse(ConnectionString);
options.Password = _pwd;
options.AbortOnConnectFail = false;
options.AllowAdmin = false;
options.KeepAlive = 30;
options.SyncTimeout = 10 * 1000;
_connection = ConnectionMultiplexer.Connect(options);
logger.Debug($"连接Redis:{ConnectionString} Password:{_pwd}");
//注册如下事件
_connection.ConnectionFailed += MuxerConnectionFailed;
_connection.ConnectionRestored += MuxerConnectionRestored;
_connection.ErrorMessage += MuxerErrorMessage;
_connection.ConfigurationChanged += MuxerConfigurationChanged;
_connection.HashSlotMoved += MuxerHashSlotMoved;
_connection.InternalError += MuxerInternalError;
}
}
}
_db = _connection.GetDatabase(dbindex);
}
public static Func<int, RedisHelper> GetInstance = (int dbindex) => { return new RedisHelper(dbindex); };
// 判断键是否存在(同步方法)
public bool KeyExists(string redisKey)
{
return _db.KeyExists(redisKey);
}
// 判断键是否存在(异步方法)
public async Task<bool> KeyExistsAsync(string redisKey)
{
return await _db.KeyExistsAsync(redisKey);
}
public bool DeleteKey(string redisKey)
{
return _db.KeyDelete(redisKey);
}
/// <summary>
/// Delete the value for string key
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<bool> DeleteKeyAsync(string redisKey)
{
return await _db.KeyDeleteAsync(redisKey);
}
public bool KeyExpire(string redisKey, TimeSpan expiry)
{
return _db.KeyExpire(redisKey,expiry);
}
public async Task<bool> KeyExpireAsync(string redisKey, TimeSpan expiry)
{
return await _db.KeyExpireAsync(redisKey, expiry);
}
#region Event
/// <summary>
/// 配置更改时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
{
Console.WriteLine("Configuration changed: " + e.EndPoint);
}
/// <summary>
/// 发生错误时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
{
logger.Error("ErrorMessage: " + e.Message);
}
/// <summary>
/// 重新建立连接之前的错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
logger.Error("ConnectionRestored: " + e.EndPoint);
}
/// <summary>
/// 连接失败 , 如果重新连接成功你将不会收到这个通知
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
logger.Error("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
}
/// <summary>
/// 更改集群
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
{
logger.Error("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
}
/// <summary>
/// redis类库错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MuxerInternalError(object sender, InternalErrorEventArgs e)
{
logger.Error("InternalError:Message" + e.Exception.Message);
}
#endregion
#region String
#region Sync
public string GetString(string redisKey)
{
return _db.StringGet(redisKey);
}
/// <summary>
/// 获取一个key的对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="redisKey"></param>
/// <returns></returns>
public T GetString<T>(string redisKey) where T : class
{
var result = _db.StringGet(redisKey);
if (string.IsNullOrEmpty(result))
{
return null;
}
return JsonConvert.DeserializeObject<T>(result);
}
/// <summary>
///
/// </summary>
/// <param name="redisKey">Redis Key</param>
/// <param name="value">保存的值</param>
/// <param name="expiry">过期时间</param>
/// <returns></returns>
public bool SetString(string redisKey, string value, TimeSpan? expiry = null)
{
return _db.StringSet(redisKey, value, expiry);
}
/// <summary>
/// 保存一个对象
/// </summary>
public bool SetString<T>(string redisKey, T obj, TimeSpan? expiry = null)
{
string json = JsonConvert.SerializeObject(obj);
return _db.StringSet(redisKey, json, expiry);
}
#endregion
#region Async
public async Task<string> GetStringAsync(string redisKey)
{
return await _db.StringGetAsync(redisKey);
}
/// <summary>
/// 获取一个key的对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="redisKey"></param>
/// <returns></returns>
public async Task<T> GetStringAsync<T>(string redisKey) where T : class
{
var result = await _db.StringGetAsync(redisKey);
if (string.IsNullOrEmpty(result))
{
return null;
}
return JsonConvert.DeserializeObject<T>(result);
}
/// <summary>
///
/// </summary>
/// <param name="redisKey">Redis Key</param>
/// <param name="value">保存的值</param>
/// <param name="expiry">过期时间</param>
/// <returns></returns>
public async Task<bool> SetStringAsync(string redisKey, string value, TimeSpan? expiry = null)
{
return await _db.StringSetAsync(redisKey, value, expiry);
}
/// <summary>
/// 保存一个对象
/// </summary>
public async Task<bool> SetStringAsync<T>(string redisKey, T obj, TimeSpan? expiry = null)
{
string json = JsonConvert.SerializeObject(obj);
return await _db.StringSetAsync(redisKey, json, expiry);
}
#endregion
#endregion
#region Hash
#region Sync
public bool DeleteHash(string redisKey, string hashKey)
{
return _db.HashDelete(redisKey, hashKey);
}
// 获取哈希表的值(同步方法)
public HashEntry[] GetHash(string redisKey)
{
return _db.HashGetAll(redisKey);
}
/// <summary>
/// 获取所有的值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="redisKey"></param>
/// <returns></returns>
public List<T> GetHash<T>(string redisKey) where T : class
{
List<T> result = new List<T>();
HashEntry[] arr = _db.HashGetAll(redisKey);
foreach (var item in arr)
{
if (!item.Value.IsNullOrEmpty)
{
result.Add(JsonConvert.DeserializeObject<T>(item.Value));
}
}
return result;
}
public T GetHash<T>(string redisKey, string hashKey) where T : class
{
RedisValue result = _db.HashGet(redisKey, hashKey);
if (string.IsNullOrEmpty(result))
{
return null;
}
return JsonConvert.DeserializeObject<T>(result);
}
// 获取哈希表的字段值(同步方法)
public string GetHashField(string redisKey, string hashKey)
{
return (string)_db.HashGet(redisKey, hashKey);
}
// 设置哈希表的字段值(同步方法)
public bool SetHash(string redisKey, string hashKey, string value)
{
return _db.HashSet(redisKey, hashKey, value);
}
// 设置哈希表的值(同步方法)
public void SetHash(string redisKey, HashEntry[] hashEntries)
{
_db.HashSet(redisKey, hashEntries);
}
public bool SetHash<T>(string redisKey, string hashKey, T t) where T : class
{
var json = JsonConvert.SerializeObject(t);
return _db.HashSet(redisKey, hashKey, json);
}
#endregion
#region Async
public async Task<bool> DeleteHashAsync(string redisKey, string hashKey)
{
return await _db.HashDeleteAsync(redisKey, hashKey);
}
// 获取哈希表的值(同步方法)
public async Task<HashEntry[]> GetHashAsync(string redisKey)
{
return await _db.HashGetAllAsync(redisKey);
}
/// <summary>
/// 获取所有的值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="redisKey"></param>
/// <returns></returns>
public async Task<List<T>> GetHashAsync<T>(string redisKey) where T : class
{
List<T> result = new List<T>();
HashEntry[] arr = await _db.HashGetAllAsync(redisKey);
foreach (var item in arr)
{
if (!item.Value.IsNullOrEmpty)
{
result.Add(JsonConvert.DeserializeObject<T>(item.Value));
}
}
return result;
}
public async Task<T> GetHashAsync<T>(string redisKey, string hashKey) where T : class
{
RedisValue result = await _db.HashGetAsync(redisKey, hashKey);
if (string.IsNullOrEmpty(result))
{
return null;
}
return JsonConvert.DeserializeObject<T>(result);
}
// 获取哈希表的字段值(同步方法)
public async Task<string> GetHashAsync(string redisKey, string hashKey)
{
return await _db.HashGetAsync(redisKey, hashKey);
}
// 设置哈希表的字段值(同步方法)
public async Task<bool> SetHashAsync(string redisKey, string hashKey, string value)
{
return await _db.HashSetAsync(redisKey, hashKey, value);
}
// 设置哈希表的值(同步方法)
public async void SetHashAsync(string redisKey, HashEntry[] hashEntries)
{
await _db.HashSetAsync(redisKey, hashEntries);
}
public async Task<bool> SetHashAsync<T>(string redisKey, string hashKey, T t) where T : class
{
var json = JsonConvert.SerializeObject(t);
return await _db.HashSetAsync(redisKey, hashKey, json);
}
#endregion
#endregion
}
}
本文来自博客园,作者:VipSoft 转载请注明原文链接:https://www.cnblogs.com/vipsoft/p/18458886