Redis总结(二)C#中如何使用redis
上一篇讲述了安装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,
- 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. 配置文件
- <!-- 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. 测试程序调用
- 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(二)集群 redis-cluster & redis主从同步
参考文档: http://geek.csdn.net/news/detail/200023 redis主从复制:https://blog.csdn.net/imxiangzi/article/deta ...
- Redis学习二 C#中如何进行这五种数据类型的操作
我在网上找了好久,就是没有找到Redis和C#结合的书,都是和别的编程语言在一起鬼混. 简单的用C#实现向Redis中插入那我中类型的数据 首先需要到NuGet 里面下载 Redis IDatabas ...
- redis系列二: linux下安装redis
下面介绍在Linux环境下,Redis的安装与配置 一. 安装 1.首先上官网下载Redis 压缩包,地址:http://redis.io/download 下载稳定版3.0即可. 2.通过远程管理工 ...
- redis(二)高级用法
redis(二)高级用法 事务 redis的事务是一组命令的集合.事务同命令一样都是redis的最小执行单元,一个事务中的命令要么执行要么都不执行. 首先需要multi命令来开始事务,用exec命令来 ...
- laravel中如何使用Redis(Redis是什么)
laravel中如何使用Redis(Redis是什么) 一.总结 一句话总结: 基于内存亦可持久化键值数据库 Redis是完全开源免费的,遵守BSD协议,是一个高性能的键值数据库.是当前最热门的的的N ...
- Redis连接(二)
Redis 命令 Redis 命令用于在 redis 服务上执行操作. 要在 redis 服务上执行命令需要一个 redis 客户端.Redis 客户端在我们之前下载的的 redis 的安装包中. 语 ...
- redis(二):Redis 命令
Redis 命令用于在 redis 服务上执行操作. 要在 redis 服务上执行命令需要一个 redis 客户端.Redis 客户端在我们之前下载的的 redis 的安装包中. 语法 Redis 客 ...
- 分布式数据存储 之 Redis(二) —— spring中的缓存抽象
分布式数据存储 之 Redis(二) -- spring中的缓存抽象 一.spring boot 中的 StringRedisTemplate 1.StringRedisTemplate Demo 第 ...
- .NET中使用Redis(二)
很久以前写了一篇文章 .NET中使用Redis 介绍了如何安装Redis服务端,以及如何在.NET中调用Redis读取数据.本文简单介绍如何设计NoSQL数据库,以及如何使用Redis来存储对象. 和 ...
随机推荐
- 使用HTML5新特性Mutation Observer实现编辑器的撤销和撤销回退操作
MutationObserver介绍 MutationObserver给开发者们提供了一种能在某个范围内的DOM树发生变化时作出适当反应的能力.该API设计用来替换掉在DOM3事件规范中引入的Mut ...
- 100726A
迭代深搜,从最深的地方搜,然后一个数被搜过了,标记用过,以后不再访问 #include<iostream> #include<cstring> #include<map& ...
- Hibernate @Formula 注解方式
1.Formula的作用 Formula的作用就是用一个查询语句动态的生成一个类的属性 就是一条select count(*)...构成的虚拟列,而不是存储在数据库里的一个字段.用比较标准的说法就是: ...
- maven2打包不同jdk版本的包
通常在一些特别情况下,我们需要为单独某一个构件打包多个不同jdk版本的包,用来支持不同的jdk,基于maven我们就可以很方便的做到这点. 1.在项目的pom文件中加入如下配置 <project ...
- C#-WinForm-客户端程序-Form基本属性
WinForm - 客服端程序(C/S) WindowsForm 的简称 客户端应用程序:是需要安装在用户电脑上才可以使用的程序,代码部分在用户电脑上执行 特点:不需要联网也可以打开使用部分功能,但现 ...
- Java中字符串的几个实例
String str=new String("abc");new 对象时,位于堆中,同时看字符串常量中是否有字符串"abc",如果没有,则进行添加,同时进行关联 ...
- C# 图片超过指定大小将压缩到指定大小不失真
using System;using System.Collections.Generic;using System.Drawing;using System.Drawing.Drawing2D;us ...
- Web前端性能优化教程03:添加Expires头
本文是Web前端性能优化系列文章中的第三篇,主要讲述添内容:加Expires头.完整教程可查看:Web前端性能优化 什么是Expires头? Expires存储的是一个用来控制缓存失效的日期.当浏览器 ...
- 【HDU 5733】tetrahedron
输入4个点三维坐标,如果是六面体,则输出内切球的球心坐标和半径. 点pi对面的面积为si,点a,b,c组成的面积=|ab叉乘ac|/2. 内心为a,公式: s0=s1+s2+s3+s4 a.x=∑si ...
- 【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 ...