打开NuGet, 点击“浏览”页面,输入“StackExchange.Redis”,进行安装。
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
namespace Common.Redis
{
public static class RedisConnectionHelp
{
private static readonly string RedisConnectionString = "127.0.0.1:6379,password=111111";//"192.168.8.73,password=111111,connectTimeout=10000,abortConnect=false";// ConfigurationManager.AppSettings["RedisExchangeHosts"];
private static readonly object Locker = new object();
private static ConnectionMultiplexer _instance;
///
/// 单例获取
///
public static ConnectionMultiplexer Instance
{
get
{
if (_instance == null || !_instance.IsConnected)
{
lock (Locker)
{
_instance = GetManager();
}
}
else if (_instance != null)
{
//LogHelper.WriteToLog("获取连接 IsConnected:" + _instance.IsConnected, "RedisConnectionHelp");
}
return _instance;
}
}
private static ConnectionMultiplexer GetManager(string connectionString = null)
{
connectionString = connectionString ?? RedisConnectionString;
var connect = ConnectionMultiplexer.Connect(connectionString);
//LogHelper.WriteToLog("获取连接:" + connectionString, "RedisConnectionHelp");
//注册如下事件
connect.ConnectionFailed += MuxerConnectionFailed;
connect.ConnectionRestored += MuxerConnectionRestored;
connect.ErrorMessage += MuxerErrorMessage;
connect.ConfigurationChanged += MuxerConfigurationChanged;
connect.HashSlotMoved += MuxerHashSlotMoved;
connect.InternalError += MuxerInternalError;
return connect;
}
#region 事件
///
/// 配置更改时
///
///
///
private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
{
//LogHelper.WriteToLog("Configuration changed: " + e.EndPoint, "RedisConnectionHelp");
}
///
/// 发生错误时
///
///
///
private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
{
//LogHelper.WriteToLog("ErrorMessage: " + e.Message, "RedisConnectionHelp");
}
///
/// 重新建立连接之前的错误
///
///
///
private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
//LogHelper.WriteToLog("ConnectionRestored: " + e.EndPoint, "RedisConnectionHelp");
}
///
/// 连接失败 , 如果重新连接成功你将不会收到这个通知
///
///
///
private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
//LogHelper.WriteToLog("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)), "RedisConnectionHelp");
}
///
/// 更改集群
///
///
///
private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
{
//LogHelper.WriteToLog("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint, "RedisConnectionHelp");
}
///
/// redis类库错误
///
///
///
private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
{
//LogHelper.WriteToLog("InternalError:Message" + e.Exception.Message, "RedisConnectionHelp");
}
#endregion 事件
}
}
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Text;
namespace Common.Redis
{
public class RedisHandler
{
private int DbId = 0;
private RedisHandler(int dbId = 0)
{
DbId = dbId;
}
public IDatabase DataBase => GetRedisConn().GetDatabase(DbId);
private static RedisHandler _instance = null;
///
/// 实例列表,每个redis的每个db建立一个Instance
///
private static Dictionary _insList = null;
///
/// 单例访问
///
public static RedisHandler Instance
{
get
{
if (null == _instance)
_instance = new RedisHandler(0);
if (null == _insList)
_insList = new Dictionary { [0] = _instance };
return _instance;
}
}
public RedisHandler this[int dbId]
{
get
{
if (dbId > 255 || dbId < 0)
throw new ArgumentOutOfRangeException(nameof(dbId), @"must be integer between 0 to 255");
if (null == _insList)
_insList = new Dictionary();
if (!_insList.ContainsKey(dbId))
_insList.Add(dbId, new RedisHandler(dbId));
var ins = _insList[dbId];
return ins;
}
}
public ConnectionMultiplexer GetRedisConn()
{
return RedisConnectionHelp.Instance;
}
public int RetryTimes { get; set; } = 1;
#region 字符串操作
///
/// 获取字符串类型的redis值
///
///
///
public RedisValue StringGet(RedisKey key)
{
var errCount = 0;
redo:
try
{
return DataBase.StringGet(key);
}
catch (Exception e)
{
if (errCount < RetryTimes)
{
errCount++;
goto redo;
}
throw;
}
}
///
/// 添加带无生命周期的数据
///
///
///
///
///
public bool StringSet(RedisKey key, RedisValue value)
{
int errCount = 0;
redo:
try
{
var ret = false;
ret = DataBase.StringSet(key, value);
return ret;
}
catch
{
if (errCount < RetryTimes)
{
errCount++;
goto redo;
}
throw;
}
}
#endregion
#region 哈希值操作
public bool HashSet(RedisKey key, RedisValue hashField, RedisValue value)
{
var errCount = 0;
redo:
try
{
return DataBase.HashSet(key, hashField, value);
}
catch (Exception e)
{
if (errCount < RetryTimes)
{
errCount++;
goto redo;
}
throw;
}
}
public RedisValue[] HashValues(RedisKey key)
{
var errCount = 0;
redo:
try
{
return DataBase.HashValues(key);
}
catch (Exception e)
{
if (errCount < RetryTimes)
{
errCount++;
goto redo;
}
throw;
}
}
#endregion
}
}
在StackExchange.Redis 下有很多方法可供调用
public class RedisController
{
//Redis DB数据库索引为0
private RedisHandler redisHelper = RedisHandler.Instance[0];
//string类型,新增key为“str”,value为“value”
public ActionResult StringSet(string key = "key", string value = "value")
{
var obj = redisHelper.StringSet(key, value);
return obj;
}
//string类型,例如通过key为“str”获取value
public ActionResult StringGet(string str = "str")
{
var obj = redisHelper.StringGet(str);
return obj.ToString();
}
//Hash类型, 新增
public ActionResult HashSet(string key , string hashField, string value)
{
var obj = redisHelper.HashSet(key, hashField, value);
return obj;
}
//Hash类型, 获取
public ActionResult HashValues(string key)
{
var obj = redisHelper.HashValues(key);
return true;
}
}