Redis总结 C#中如何使用redis
转载自:https://www.cnblogs.com/zhangweizhong/p/4972348.html
本篇着重讲解.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 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
94 
95 
96 
97 
98 
99 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129 
130 
131 
132 
133 
134 
135 
136 
137 
138 
139 
140 
141 
142 
143 
144 
145 
146 
147 
148 
149 
150 
151 
152 
153 
154 
155 
156 
157 
158 
159 
160 
161 
162 
163 
164 
165 
166 
167 
168 
169 
170 
171 
172 
173 
174 
175 
176 
177 
178 
179 
180 
181 
182 
183 
184 
185 
186 
187 
188 
189 
190 
191 
 | 
using System;using System.Collections.Generic;using System.Configuration;using System.Linq;using System.Text;using System.Web;using ServiceStack.Common.Extensions;using ServiceStack.Redis;using ServiceStack.Logging;namespace Weiz.Redis.RedisTest{    public class RedisCacheHelper    {        private static readonly PooledRedisClientManager pool = null;        private static readonly string[] redisHosts = null;        public static int RedisMaxReadPool = int.Parse(ConfigurationManager.AppSettings["redis_max_read_pool"]);        public static int RedisMaxWritePool = int.Parse(ConfigurationManager.AppSettings["redis_max_write_pool"]);        static RedisCacheHelper()        {            var redisHostStr = ConfigurationManager.AppSettings["redis_server_session"];            if (!string.IsNullOrEmpty(redisHostStr))            {                redisHosts = redisHostStr.Split(',');                if (redisHosts.Length > 0)                {                    pool = new PooledRedisClientManager(redisHosts, redisHosts,                        new RedisClientManagerConfig()                        {                            MaxWritePoolSize = RedisMaxWritePool,                            MaxReadPoolSize = RedisMaxReadPool,                            AutoStart = true                        });                }            }        }        public static void Add<T>(string key, T value, DateTime expiry)        {            if (value == null)            {                return;            }            if (expiry <= DateTime.Now)            {                Remove(key);                return;            }            try            {                if (pool != null)                {                    using (var r = pool.GetClient())                    {                        if (r != null)                        {                            r.SendTimeout = 1000;                            r.Set(key, value, expiry - DateTime.Now);                        }                    }                }            }            catch (Exception ex)            {                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);            }        }        public static void Add<T>(string key, T value, TimeSpan slidingExpiration)        {            if (value == null)            {                return;            }            if (slidingExpiration.TotalSeconds <= 0)            {                Remove(key);                return;            }            try            {                if (pool != null)                {                    using (var r = pool.GetClient())                    {                        if (r != null)                        {                            r.SendTimeout = 1000;                            r.Set(key, value, slidingExpiration);                        }                    }                }            }            catch (Exception ex)            {                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);            }        }        public static T Get<T>(string key)        {            if (string.IsNullOrEmpty(key))            {                return default(T);            }            T obj = default(T);            try            {                if (pool != null)                {                    using (var r = pool.GetClient())                    {                        if (r != null)                        {                            r.SendTimeout = 1000;                            obj = r.Get<T>(key);                        }                    }                }            }            catch (Exception ex)            {                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "获取", key);            }            return obj;        }        public static void Remove(string key)        {            try            {                if (pool != null)                {                    using (var r = pool.GetClient())                    {                        if (r != null)                        {                            r.SendTimeout = 1000;                            r.Remove(key);                        }                    }                }            }            catch (Exception ex)            {                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "删除", key);            }        }        public static bool Exists(string key)        {            try            {                if (pool != null)                {                    using (var r = pool.GetClient())                    {                        if (r != null)                        {                            r.SendTimeout = 1000;                            return r.ContainsKey(key);                        }                    }                }            }            catch (Exception ex)            {                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "是否存在", key);            }            return false;        }    }} | 
说明:RedisCacheHelper 使用的是客户端链接池模式,这样的存取效率应该是最高的。同时也更方便的支持读写分离,均衡负载。
3. 配置文件
| 
 1 
2 
3 
4 
5 
6 
 | 
<!-- redis Start   --><add key="SessionExpireMinutes" value="180" /><add key="redis_server_session" value="127.0.0.1:6379" /><add key="redis_max_read_pool" value="3" /><add key="redis_max_write_pool" value="1" /><!--redis end--> | 
4. 测试程序调用
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
 | 
class Program    {        static void Main(string[] args)        {            Console.WriteLine("Redis写入缓存:zhong");            RedisCacheHelper.Add("zhong", "zhongzhongzhong", DateTime.Now.AddDays(1));            Console.WriteLine("Redis获取缓存:zhong");            string str3 = RedisCacheHelper.Get<string>("zhong");            Console.WriteLine(str3);            Console.WriteLine("Redis获取缓存:nihao");            string str = RedisCacheHelper.Get<string>("nihao");            Console.WriteLine(str);            Console.WriteLine("Redis获取缓存:wei");            string str1 = RedisCacheHelper.Get<string>("wei");            Console.WriteLine(str1);            Console.ReadKey();        }    } | 
5. 输出结果
    
Redis总结 C#中如何使用redis的更多相关文章
- redis(Springboot中封装整合redis,java程序如何操作redis的5种基本数据类型)
		
平常测试redis操作命令,可能用的是cmd窗口 操作redis,记录一下 java程序操作reids, 操作redis的方法 可以用Jedis ,在springboot 提供了两种 方法操作 Red ...
 - Redis 在新浪微博中的应用
		
Redis 在新浪微博中的应用 Redis简介 1. 支持5种数据结构 支持strings, hashes, lists, sets, sorted setsstring是很好的存储方式,用来做计数存 ...
 - redis之(十五)redis的集群中的哨兵角色
		
一:redis集群的哨兵的目的是什么?. (1)监控主redis和从redis数据库是否正常运行 (2)主redis出现故障,自动将其中一台从redis升级为主redis.将原先的主redis转变成从 ...
 - redis 在 windows 中的安装
		
redis 在 windows 中的安装 redis 官方并没有提供 redis 的 windows 版本.但是微软提供了 redis 的 windows 版本.有2.8和3.0版本.3.0版本支持集 ...
 - Redis 在NETCore中的应用
		
Redis 在NETCore中的应用 Redis 在netFramework中的应用 也一样 新建.NETCORE(webapi)项目 安装NuGet //查询NuGet语句 Find-Packag ...
 - Redis系列(五):Redis的RESP协议详解
		
一.什么是RESP Redis是Redis序列化协议,Redis客户端RESP协议与Redis服务器通信.Redis协议在以下几点之间做出了折衷: 简单的实现 快速地被计算机解析 简单得可以能被人工解 ...
 - windows安装redis并为php5.4添加redis扩展
		
第一步 安装包下载 首先下载php5.4对应版本的php_igbinary.dll,php_redis.dll扩展.(php7以后可不需要php_igbinary.dl这个文件了) 链接:https: ...
 - 关于redis的几件小事(十)redis cluster模式
		
redis cluster是redis提供的集群模式. 1.redis cluster的架构 ①可以有多个master node,每个master node 都可以挂载多个slave node. ②读 ...
 - [Redis] 万字长文带你总结Redis,助你面试升级打怪
		
文章目录 Redis的介绍.优缺点.使用场景 Linux中的安装 常用命令 Redis各个数据类型及其使用场景 Redis字符串(String) Redis哈希(Hash) Redis列表(List) ...
 
随机推荐
- python多线程学习(一)
			
python多线程.多进程 初探 原先刚学Java的时候,多线程也学了几天,后来一直没用到.然后接触python的多线程的时候,貌似看到一句"python多线程很鸡肋",于是乎直接 ...
 - java中的12种锁
			
java中很多地方会涉及到锁,比如java代码并发场景,DB中的并发场景,分布式中的锁....你知道几种呢?下面来看看常见的11种锁 1. 乐观锁/悲观锁 这两个概念是人们对java中各种锁总结提出的 ...
 - Hadoop单节点启动分布式伪集群
			
emm~ 写这篇博客只是手痒,因为开发环境用单节点就够了,生产环境肯定是真实集群,所以这个伪分布式纯属娱乐而已. 配置HDFS1. 安装好一台hadoop,可以参考这篇博客.2. 在hadoop目录下 ...
 - Angular获取dom元素,以及父子组建之间相互传值
			
1.使用原生js代码获取dom元素 在ts文件中有一个ngOnInit()的方法,这个方式是指在模块加载完毕之后并不是dom加载完毕,也就是说如果你的dom元素中使用的angular的指令,然后想在这 ...
 - [转载]static in Java
			
来源:https://www.cnblogs.com/chenssy/p/3386721.html 一. static代表着什么 在Java中并不存在全局变量的概念,但是我们可以通过static来实现 ...
 - vsCode 前端插件推荐-和插件配置
			
参考自网站:https://segmentfault.com/a/1190000011779959 插件安装完成之后,还要对一些插件进行配置,例如: vetur默认配置, 配置的过程: 打开 文件 & ...
 - 启动web项目报错:The server time zone value '�й���ʱ��' is unrecognized or represents more than one time zone.
			
解决: 在application.properties配置文件中的添加标红部分 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/miaosha?se ...
 - 好用的 python 工具集合
			
图标处理小程序, 妈妈再也不用担心我不会制作图标了 # PythonMargick包可以到Unofficial Windows Binaries for Python Extension Packag ...
 - 转载Google TPU论文
			
选自 Google Drive 作者:Norman P. Jouppi 等 痴笑@矽说 编译 该论文将正式发表于 ISCA 2017 从去年七月起,Google就号称了其面向深度学习的专用集成电路(A ...
 - Chrome去掉标签页8个框
			
最终效果: 解决思路: 在标签页鼠标右击弹出的菜单项中存在“查看页面源码”一项,由此可确定chrome的标签页是由一个html页面控制的,只要修改其页面源码便能去掉8个框. 经网上查阅确定了标签页的源 ...