上一篇讲述了安装redis《Redis总结(一)Redis安装》,同时也大致介绍了redis的优势和应用场景。本篇着重讲解.NET中如何使用redis和C#。

  Redis官网提供了很多开源的C#客户端。例如,Nhiredis ,ServiceStack.Redis ,StackExchange.Redis等。其中ServiceStack.Redis应该算是比较流行的。它提供了一整套从Redis数据结构都强类型对象转换的机制并将对象json序列化。所以这里只介绍ServiceStack.Redis,它也是目前我们产品中所使用的客户端。

  ServiceStack.Redis地址https://github.com/ServiceStack/ServiceStack.Redis

  1. 建立一个控制台应用程序,并引用以下ServiceStack.Redis相关的四个类库。或者通过Nuget进行安装Redis常用组件ServiceStack.Redis。 下载示例代码

  2. 创建一个Redis操作的公用类RedisCacheHelper,

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Web;
  7. using ServiceStack.Common.Extensions;
  8. using ServiceStack.Redis;
  9. using ServiceStack.Logging;
  10.  
  11. namespace Weiz.Redis.RedisTest
  12. {
  13. public class RedisCacheHelper
  14. {
  15. private static readonly PooledRedisClientManager pool = null;
  16. private static readonly string[] redisHosts = null;
  17. public static int RedisMaxReadPool = int.Parse(ConfigurationManager.AppSettings["redis_max_read_pool"]);
  18. public static int RedisMaxWritePool = int.Parse(ConfigurationManager.AppSettings["redis_max_write_pool"]);
  19.  
  20. static RedisCacheHelper()
  21. {
  22. var redisHostStr = ConfigurationManager.AppSettings["redis_server_session"];
  23.  
  24. if (!string.IsNullOrEmpty(redisHostStr))
  25. {
  26. redisHosts = redisHostStr.Split(',');
  27.  
  28. if (redisHosts.Length > 0)
  29. {
  30. pool = new PooledRedisClientManager(redisHosts, redisHosts,
  31. new RedisClientManagerConfig()
  32. {
  33. MaxWritePoolSize = RedisMaxWritePool,
  34. MaxReadPoolSize = RedisMaxReadPool,
  35. AutoStart = true
  36. });
  37. }
  38. }
  39. }
  40. public static void Add<T>(string key, T value, DateTime expiry)
  41. {
  42. if (value == null)
  43. {
  44. return;
  45. }
  46.  
  47. if (expiry <= DateTime.Now)
  48. {
  49. Remove(key);
  50.  
  51. return;
  52. }
  53.  
  54. try
  55. {
  56. if (pool != null)
  57. {
  58. using (var r = pool.GetClient())
  59. {
  60. if (r != null)
  61. {
  62. r.SendTimeout = 1000;
  63. r.Set(key, value, expiry - DateTime.Now);
  64. }
  65. }
  66. }
  67. }
  68. catch (Exception ex)
  69. {
  70. string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
  71. }
  72.  
  73. }
  74.  
  75. public static void Add<T>(string key, T value, TimeSpan slidingExpiration)
  76. {
  77. if (value == null)
  78. {
  79. return;
  80. }
  81.  
  82. if (slidingExpiration.TotalSeconds <= 0)
  83. {
  84. Remove(key);
  85.  
  86. return;
  87. }
  88.  
  89. try
  90. {
  91. if (pool != null)
  92. {
  93. using (var r = pool.GetClient())
  94. {
  95. if (r != null)
  96. {
  97. r.SendTimeout = 1000;
  98. r.Set(key, value, slidingExpiration);
  99. }
  100. }
  101. }
  102. }
  103. catch (Exception ex)
  104. {
  105. string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
  106. }
  107.  
  108. }
  109.  
  110. public static T Get<T>(string key)
  111. {
  112. if (string.IsNullOrEmpty(key))
  113. {
  114. return default(T);
  115. }
  116.  
  117. T obj = default(T);
  118.  
  119. try
  120. {
  121. if (pool != null)
  122. {
  123. using (var r = pool.GetClient())
  124. {
  125. if (r != null)
  126. {
  127. r.SendTimeout = 1000;
  128. obj = r.Get<T>(key);
  129. }
  130. }
  131. }
  132. }
  133. catch (Exception ex)
  134. {
  135. string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "获取", key);
  136. }
  137.  
  138. return obj;
  139. }
  140.  
  141. public static void Remove(string key)
  142. {
  143. try
  144. {
  145. if (pool != null)
  146. {
  147. using (var r = pool.GetClient())
  148. {
  149. if (r != null)
  150. {
  151. r.SendTimeout = 1000;
  152. r.Remove(key);
  153. }
  154. }
  155. }
  156. }
  157. catch (Exception ex)
  158. {
  159. string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "删除", key);
  160. }
  161.  
  162. }
  163.  
  164. public static bool Exists(string key)
  165. {
  166. try
  167. {
  168. if (pool != null)
  169. {
  170. using (var r = pool.GetClient())
  171. {
  172. if (r != null)
  173. {
  174. r.SendTimeout = 1000;
  175. return r.ContainsKey(key);
  176. }
  177. }
  178. }
  179. }
  180. catch (Exception ex)
  181. {
  182. string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "是否存在", key);
  183. }
  184.  
  185. return false;
  186. }
  187. }
  188. }

  说明:RedisCacheHelper 使用的是客户端链接池模式,这样的存取效率应该是最高的。同时也更方便的支持读写分离,均衡负载。

  3. 配置文件

  1. <!-- redis Start -->
  2. <add key="SessionExpireMinutes" value="180" />
  3. <add key="redis_server_session" value="127.0.0.1:6379" />
  4. <add key="redis_max_read_pool" value="3" />
  5. <add key="redis_max_write_pool" value="1" />
  6. <!--redis end-->

 

  4. 测试程序调用

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. Console.WriteLine("Redis写入缓存:zhong");
  6.  
  7. RedisCacheHelper.Add("zhong", "zhongzhongzhong", DateTime.Now.AddDays(1));
  8.  
  9. Console.WriteLine("Redis获取缓存:zhong");
  10.  
  11. string str3 = RedisCacheHelper.Get<string>("zhong");
  12.  
  13. Console.WriteLine(str3);
  14.  
  15. Console.WriteLine("Redis获取缓存:nihao");
  16. string str = RedisCacheHelper.Get<string>("nihao");
  17. Console.WriteLine(str);
  18.  
  19. Console.WriteLine("Redis获取缓存:wei");
  20. string str1 = RedisCacheHelper.Get<string>("wei");
  21. Console.WriteLine(str1);
  22.  
  23. Console.ReadKey();
  24. }
  25. }

  

  5. 输出结果

    

Redis总结(二)C#中如何使用redis的更多相关文章

  1. redis(二)集群 redis-cluster & redis主从同步

    参考文档: http://geek.csdn.net/news/detail/200023 redis主从复制:https://blog.csdn.net/imxiangzi/article/deta ...

  2. Redis学习二 C#中如何进行这五种数据类型的操作

    我在网上找了好久,就是没有找到Redis和C#结合的书,都是和别的编程语言在一起鬼混. 简单的用C#实现向Redis中插入那我中类型的数据 首先需要到NuGet 里面下载 Redis IDatabas ...

  3. redis系列二: linux下安装redis

    下面介绍在Linux环境下,Redis的安装与配置 一. 安装 1.首先上官网下载Redis 压缩包,地址:http://redis.io/download 下载稳定版3.0即可. 2.通过远程管理工 ...

  4. redis(二)高级用法

    redis(二)高级用法 事务 redis的事务是一组命令的集合.事务同命令一样都是redis的最小执行单元,一个事务中的命令要么执行要么都不执行. 首先需要multi命令来开始事务,用exec命令来 ...

  5. laravel中如何使用Redis(Redis是什么)

    laravel中如何使用Redis(Redis是什么) 一.总结 一句话总结: 基于内存亦可持久化键值数据库 Redis是完全开源免费的,遵守BSD协议,是一个高性能的键值数据库.是当前最热门的的的N ...

  6. Redis连接(二)

    Redis 命令 Redis 命令用于在 redis 服务上执行操作. 要在 redis 服务上执行命令需要一个 redis 客户端.Redis 客户端在我们之前下载的的 redis 的安装包中. 语 ...

  7. redis(二):Redis 命令

    Redis 命令用于在 redis 服务上执行操作. 要在 redis 服务上执行命令需要一个 redis 客户端.Redis 客户端在我们之前下载的的 redis 的安装包中. 语法 Redis 客 ...

  8. 分布式数据存储 之 Redis(二) —— spring中的缓存抽象

    分布式数据存储 之 Redis(二) -- spring中的缓存抽象 一.spring boot 中的 StringRedisTemplate 1.StringRedisTemplate Demo 第 ...

  9. .NET中使用Redis(二)

    很久以前写了一篇文章 .NET中使用Redis 介绍了如何安装Redis服务端,以及如何在.NET中调用Redis读取数据.本文简单介绍如何设计NoSQL数据库,以及如何使用Redis来存储对象. 和 ...

随机推荐

  1. 使用HTML5新特性Mutation Observer实现编辑器的撤销和撤销回退操作

     MutationObserver介绍 MutationObserver给开发者们提供了一种能在某个范围内的DOM树发生变化时作出适当反应的能力.该API设计用来替换掉在DOM3事件规范中引入的Mut ...

  2. 100726A

    迭代深搜,从最深的地方搜,然后一个数被搜过了,标记用过,以后不再访问 #include<iostream> #include<cstring> #include<map& ...

  3. Hibernate @Formula 注解方式

    1.Formula的作用 Formula的作用就是用一个查询语句动态的生成一个类的属性 就是一条select count(*)...构成的虚拟列,而不是存储在数据库里的一个字段.用比较标准的说法就是: ...

  4. maven2打包不同jdk版本的包

    通常在一些特别情况下,我们需要为单独某一个构件打包多个不同jdk版本的包,用来支持不同的jdk,基于maven我们就可以很方便的做到这点. 1.在项目的pom文件中加入如下配置 <project ...

  5. C#-WinForm-客户端程序-Form基本属性

    WinForm - 客服端程序(C/S) WindowsForm 的简称 客户端应用程序:是需要安装在用户电脑上才可以使用的程序,代码部分在用户电脑上执行 特点:不需要联网也可以打开使用部分功能,但现 ...

  6. Java中字符串的几个实例

    String str=new String("abc");new 对象时,位于堆中,同时看字符串常量中是否有字符串"abc",如果没有,则进行添加,同时进行关联 ...

  7. C# 图片超过指定大小将压缩到指定大小不失真

    using System;using System.Collections.Generic;using System.Drawing;using System.Drawing.Drawing2D;us ...

  8. Web前端性能优化教程03:添加Expires头

    本文是Web前端性能优化系列文章中的第三篇,主要讲述添内容:加Expires头.完整教程可查看:Web前端性能优化 什么是Expires头? Expires存储的是一个用来控制缓存失效的日期.当浏览器 ...

  9. 【HDU 5733】tetrahedron

    输入4个点三维坐标,如果是六面体,则输出内切球的球心坐标和半径. 点pi对面的面积为si,点a,b,c组成的面积=|ab叉乘ac|/2. 内心为a,公式: s0=s1+s2+s3+s4 a.x=∑si ...

  10. 【CodeForces 261B】Maxim and Restaurant(DP,期望)

    题目链接 第一种解法是$O(n^3*p)$的:f[i][j][k]表示前i个人进j个人长度为k有几种方案(排列固定为123..n时).$f[i][j][k]=f[i-1][j][k]+f[i-1][j ...