一、引入StackExchange.Redis

打开NuGet, 点击“浏览”页面,输入“StackExchange.Redis”,进行安装。

二、创建Redis链接管理RedisConnectionHelp

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;/// <summary>/// 单例获取/// </summary>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 事件/// <summary>/// 配置更改时/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e){//LogHelper.WriteToLog("Configuration changed: " + e.EndPoint, "RedisConnectionHelp");}/// <summary>/// 发生错误时/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e){//LogHelper.WriteToLog("ErrorMessage: " + e.Message, "RedisConnectionHelp");}/// <summary>/// 重新建立连接之前的错误/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e){//LogHelper.WriteToLog("ConnectionRestored: " + e.EndPoint, "RedisConnectionHelp");}/// <summary>/// 连接失败 , 如果重新连接成功你将不会收到这个通知/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e){//LogHelper.WriteToLog("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)), "RedisConnectionHelp");}/// <summary>/// 更改集群/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e){//LogHelper.WriteToLog("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint, "RedisConnectionHelp");}/// <summary>/// redis类库错误/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private static void MuxerInternalError(object sender, InternalErrorEventArgs e){//LogHelper.WriteToLog("InternalError:Message" + e.Exception.Message, "RedisConnectionHelp");}#endregion 事件}
}

三、创建Redis处理方法

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;/// <summary>/// 实例列表,每个redis的每个db建立一个Instance/// </summary>private static Dictionary<int, RedisHandler> _insList = null;/// <summary>/// 单例访问/// </summary>public static RedisHandler Instance{get{if (null == _instance)_instance = new RedisHandler(0);if (null == _insList)_insList = new Dictionary<int, RedisHandler> { [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<int, RedisHandler>();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 字符串操作/// <summary>/// 获取字符串类型的redis值/// </summary>/// <param name="key"></param>/// <returns></returns>public RedisValue StringGet(RedisKey key){var errCount = 0;redo:try{return DataBase.StringGet(key);}catch (Exception e){if (errCount < RetryTimes){errCount++;goto redo;}throw;}}/// <summary>/// 添加带无生命周期的数据/// </summary>/// <param name="key"></param>/// <param name="value"></param>/// <param name="expire"></param>/// <returns></returns>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数据库索引为0private RedisHandler redisHelper = RedisHandler.Instance[0];//string类型,新增key为“str”,value为“value”  public ActionResult<bool> StringSet(string key = "key", string value = "value"){var obj = redisHelper.StringSet(key, value);return obj;}//string类型,例如通过key为“str”获取value  public ActionResult<string> StringGet(string str = "str"){var obj = redisHelper.StringGet(str);return obj.ToString();}//Hash类型, 新增public ActionResult<bool> HashSet(string key , string hashField, string value){var obj = redisHelper.HashSet(key, hashField, value);return obj;}//Hash类型, 获取public ActionResult<bool> HashValues(string key){var obj = redisHelper.HashValues(key);return true;}
}

欢迎加群,日用儿童母婴,分享大牌淘宝京东优惠券

.NET Core StackExchange.Redis使用方法相关推荐

  1. .net core 使用redis 基于 StackExchange.Redis

    一.添加引用包 StackExchange.Redis Microsoft.Extensions.Configuration 二.修改配置文件 appsettings.json {"Redi ...

  2. stackexchange.mysql_.net core使用redis基于StackExchange.Redis

    .net core使用redis基于StackExchange.Redis教程,具体如下 一.添加引用包 StackExchange.Redis Microsoft.Extensions.Config ...

  3. 【BCVP更新】StackExchange.Redis 的异步开发方式

    有哪些习惯 坚持 LESS IS MORE,SIMPLER IS BETTER THAN MORE 你一定会有很大的收获 各种小问题? 如果你之前用过Redis的话,肯定会使用过StackExchan ...

  4. StackExchange.Redis客户端读写主从配置,以及哨兵配置

    今天简单分享一下StackExchange.Redis客户端中配置主从分离以及哨兵的配置. 关于哨兵如果有不了解的朋友,可以看我之前的一篇分享,当然主从复制文章也可以找到.http://www.cnb ...

  5. StackExchange.Redis 使用-配置

    Configuration redis有很多不同的方法来配置连接字符串 , StackExchange.Redis 提供了一个丰富的配置模型,当调用Connect 或者 ConnectAsync 时需 ...

  6. StackExchange.Redis 访问封装类

    最近需要在C#中使用Redis,在Redis的官网找到了ServiceStack.Redis,最后在测试的时候发现这是个坑,4.0已上已经收费,后面只好找到3系列的最终版本,最后测试发现还是有BUG或 ...

  7. StackExchange.Redis通用封装类分享(转)

    阅读目录 ConnectionMultiplexer 封装 RedisHelper 通用操作类封 String类型的封装 List类型的封装 Hash类型的封装 SortedSet 类型的封装 key ...

  8. StackExchange.Redis 官方文档(二) Configuration

    配置 有多种方式可以配置redis,StackExchange.Redis提供了一个丰富的配置模型,在执行Connect (or ConnectAsync) 时被调用: var conn = Conn ...

  9. StackExchange.Redis 使用 (一)

    在StackExchange.Redis中最重要的对象是ConnectionMultiplexer类, 它存在于StackExchange.Redis命名空间中. 这个类隐藏了Redis服务的操作细节 ...

最新文章

  1. python程序设计语言是什么类型的语言-Python 是弱类型的语言 强类型和弱类型的语言区别...
  2. c/c++比较灵活的方法:回调函数和函数指针
  3. tensorflow(centos 7.0 64)安装
  4. matlab指定间隔符,在matlab中为.dat文件指定小数分隔符[复制]
  5. 计算机主机部件与外设的工作原理,计算机组成原理名词解释和简答
  6. Oracle 创建用户 scott 例
  7. SQL LIKE 操作符
  8. python循环次数查询_大数据量Mysql查询后经过循环使用python分片
  9. Windows 操作小技巧 之一(持续更新)
  10. JavaScript闭包理解【关键字:普通函数、变量访问作用域、闭包、解决获取元素标签索引】...
  11. java day60【 Spring 中的 JdbcTemplate[会用] 、Spring 中的事务控制 、Spring5 的新特性[了解] 】...
  12. linux系统ping地址端口,linux ping 带端口
  13. 系统发育树操作神器-TreeTools-持续更新
  14. 安卓QQ聊天记录导出、备份完全攻略
  15. 从 0 搭建 Vite 3 + Vue 3 前端工程化项目
  16. java实现Blowfish算法加密解密
  17. wps文档怎样去除广告
  18. 中国离合器行业运行态势及产销需求预测报告2021-2027年
  19. RecyclerView安卓androidx.widget.RecyclerView
  20. 保姆式教学--教室友从买服务器到怎么搭建内网隧道

热门文章

  1. Docker创建Docker Swarm集群节点
  2. 艾司博讯:拼多多开店保证金必须交吗
  3. findIndex的使用
  4. mysql中括号的表达_Mysql中数据类型括号中的数字代表的含义
  5. 忙前忙后的滴滴,真的能做好自动驾驶?
  6. Mac 请尝试使用字符较少,或不含标点符号的名称解决方法
  7. 计算机公式固定数值符号,中级无纸化机考 数学公式/符号你会输入吗?
  8. CCS7.3安装教程适用于win7系统,并且解决微软更新补丁安装不成功的问题
  9. Centos Stream 9 换DNF源
  10. visual studio编译boost1.73.0静态库32位和64位