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. JavaScript继承与聚合

    一,继承 第一种方式:类与被继承类直接耦合度高 1,首先,准备一个可以被继承的类(父类),例如 //创建一个人员类 function Person(name) {//现在Person里面的域是由Per ...

  2. 2.Apache + Tomcat + mod_jk实现集群服务

    转自:http://www.cnblogs.com/dennisit/p/3370220.html Tomcat中的集群原理是通过组播的方式进行节点的查找并使用TCP连接进行会话的复制. 实现效果:用 ...

  3. k8s 基础 k8s架构和组件

    k8s 的总架构图

  4. c语言基础 c和指针

    句子 c规定数组名代表数组首元素的地址 如果&a 则代表整个数组 没有内存哪来的指针 数据类型的本质:固定大小内存的别名 变量的本质:(一段连续)内存空间的别名,内存空间的标号 指针是一种数据 ...

  5. Eclipse调试Java程序技巧

    主要步骤.Debug As"->"Java Application".双击设置断点,F5是跳进,F6是执行下一步,F7是跳出 在看这篇文章前,我推荐你看一下Ecli ...

  6. 实现reentrantlock和读写锁

    1 可以手动实现一个类似reentrantlock的工具,首先要维护一个state的标志,代表当前是否有线程已经使用资源.线程lock的时候, 会用cas给state加1,其他线程检测状态.另外需要维 ...

  7. MySql数据库数据更新操作其高级应用

    数据更新操作有3种:向表中添加数据.修改表中的数据和删除表中的数据. 用来演示的数据表用student.course.sc三个数据表,数据表具体内容在:PHP和MySql数据库,如何获取每个分类的记录 ...

  8. 获取显示屏的个数和分辨率 --- 通过使用OpenGL的GLFW库

    获取显示屏的个数和分辨率 - 通过使用OpenGL的GLFW库 程序 #include <iostream> // GLFW #include <GLFW/glfw3.h> i ...

  9. Ubuntu下crontab命令的用法

    cron是一个Linux下的后台进程,用来定期的执行一些任务.因为我用的是Ubuntu,所以这篇文章中的所有命令也只能保证在Ubuntu下有效,但其他系统应该也差不多. 想要让cron执行你指定的任务 ...

  10. github的简单操作

    之前初学过一点git版本控制工具,利用github做仓库,照着github上的文档练习的了一下.不过那只篇只是照虎画猫(我的水平只能照着老虎画个猫模样,嘻嘻!). 最近在学hibernate,公司与家 ...