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. 输出结果

    

出处:http://www.fpeach.com/

ServiceStack.Redis 使用的更多相关文章

  1. .Net使用Redis详解之ServiceStack.Redis(七)

    序言 本篇从.Net如何接入Reis开始,直至.Net对Redis的各种操作,为了方便学习与做为文档的查看,我做一遍注释展现,其中会对list的阻塞功能和事务的运用做二个案例,进行记录学习. Redi ...

  2. ServiceStack.Redis订阅发布服务的调用(Z)

      1.Redis订阅发布介绍Redis订阅发布是一种消息通信模式:发布者(publisher)发送消息,订阅者(Subscriber)接受消息.类似于设计模式中的观察者模式.发布者和订阅者之间使用频 ...

  3. serviceStack.Redis 在PooledRedisClientManager 中设置密码

    ServiceStack.Redis 是一个C#访问Redis的客户端,可以说可以通过它实现所有需要Redis-Cli的功能.但是今天我在主Redis 实例设置了访问密码,而在slave 上没有设置, ...

  4. ServiceStack.Redis订阅发布服务的调用

    1.Redis订阅发布介绍 Redis订阅发布是一种消息通信模式:发布者(publisher)发送消息,订阅者(Subscriber)接受消息.类似于设计模式中的观察者模式. 发布者和订阅者之间使用频 ...

  5. Redis简介、与memcached比较、存储方式、应用场景、生产经验教训、安全设置、key的建议、安装和常用数据类型介绍、ServiceStack.Redis使用(1)

    1.NOSQL简介 nosql的产生并不是要彻底的代替关系型数据库,而是作为传统关系型数据库的一个补充. Facebook和360使用Cassandra来存储海量社交数据 Twitter在其url抓取 ...

  6. ServiceStack.Redis 使用教程

    http://www.cnblogs.com/shanyou/archive/2011/11/10/2245082.html https://github.com/ServiceStack/Servi ...

  7. 在使用Redis的客户端连接工具ServiceStack.Redis要注意的问题

    在使用Redis的客户端连接工具ServiceStack.Redis要注意的问题   Redis是一个非常NB的内存级的数据库,我们可以把很多”热数据“(即读写非常多的数据)放入其中来操作,这样就减少 ...

  8. 关于 ServiceStack.Redis 4.0 License

    今天更新了框架中的Redis驱动ServiceStack.Redis,最新版本4.0.5.0. 在做简单压力测试时出现异常,提示每小时允许6000个请求. The free-quota limit o ...

  9. ServiceStack.Redis.RedisNativeClient的方法“get_Db”没有实现

    Redis 4.0.0.0版本已经开始收费 Redis 4.0.5.0 已经完成收费 今日在更换Redis版本时 出现了ServiceStack.Redis.RedisNativeClient的方法“ ...

  10. ServiceStack.Redis

    什么是Redis 首先,简述一下什么是Redis. Redis是一个开源.支持网络.基于内存.键值对存储数据库,使用ANSI C编写.从2013年5月开始,Redis的开发由Pivotal赞助.在这之 ...

随机推荐

  1. C笔试题(二)

    /* 现在有一个数组 我们可以定义数组的子数组 如 数组 1 3 4 2 5 8 7 它的子数组可以是 1 3 4 3 4 2 5 等等 请写一个算法 找一个子数组 这个子数组递增不减少 并且是满足递 ...

  2. 恢复到版本并销毁之后的git提交记录

    git reset --hard HEAD~1(或者你想要的版本号) git push --force # 千万注意:此操作无法恢复

  3. require用法及源码解析

    一.require()的基本用法 require语句内部逻辑: 当 Node 遇到 require(X) 时,按下面的顺序处理. (1)如果 X 是内置模块(比如 require('http'))  ...

  4. Spring入门第二十四课

    Spring对JDBC的支持 直接看代码: db.properties jdbc.user=root jdbc.password=logan123 jdbc.driverClass=com.mysql ...

  5. 20169201 2016-2017-2 实验二《Java面向对象程序设计》

    实验一:程序设计中临时变量的使用 代码托管 1.删除数组中的元素5 for(int i = 4; i < arr.length - 1; i ++){ arr[i] = arr[i + 1]; ...

  6. NYOJ 喷水装置(二)

    题目转换成,每个水龙头在横坐标方向上覆盖的长度区间,转换后的问题就有点像会场安排问题了,然后接下来选的方案依据贪心,我们队这些个区间进行排序,依照区间的左端点按从小到大排序,然后从左往右选取,条件是当 ...

  7. JsonParse类

    using System.Data; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using Syst ...

  8. DES的雪崩效应分析

    明文固定,密钥改变一个字节 假定明文为11111111(00000001 00000001 00000001 00000001 00000001 00000001 00000001 00000001) ...

  9. Python:列表也能拆包?

    前几天,微信学习群里有个小伙伴在看书时遇到了这样一个问题,在群里提问,看下图: 这是常用的 matplotlib 库,只是一般我们调用 plot 方法绘图时,不会去关心它的返回值.然而 plt1, = ...

  10. ProtoBuf练习

    环境设置 项目地址 https://github.com/silvermagic/ProtoBufDev.git 操作系统 64位 Fedora 24 安装protobuf $ git clone h ...