需要注意的是:ServiceStack.Redis 中GetClient()方法,只能拿到Master redis中获取连接,而拿不到slave 的readonly连接。这样 slave起到了冗余备份的作用,读的功能没有发挥出来,如果并发请求太多的话,则Redis的性能会有影响。

    所以,我们需要的写入和读取的时候做一个区分,写入的时候,调用client.GetClient() 来获取writeHosts的Master的redis 链接。读取,则调用client.GetReadOnlyClient()来获取的readonlyHost的 Slave的redis链接。

    或者可以直接使用client.GetCacheClient() 来获取一个连接,他会在写的时候调用GetClient获取连接,读的时候调用GetReadOnlyClient获取连接,这样可以做到读写分离,从而利用redis的主从复制功能。

    1. 配置文件 app.config

  <!-- redis Start   -->
    <add key="SessionExpireMinutes" value="180" />
    <add key="redis_server_master_session" value="127.0.0.1:6379" />
    <add key="redis_server_slave_session" value="127.0.0.1:6380" />
    <add key="redis_max_read_pool" value="300" />
    <add key="redis_max_write_pool" value="100" />
    <!--redis end-->

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.Common
{
    public class RedisCacheHelper
    {
        private static readonly PooledRedisClientManager pool = null;
        private static readonly string[] writeHosts = null;
        private static readonly string[] readHosts = 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 redisMasterHost = ConfigurationManager.AppSettings["redis_server_master_session"];
            var redisSlaveHost = ConfigurationManager.AppSettings["redis_server_slave_session"];

if (!string.IsNullOrEmpty(redisMasterHost))
            {
                writeHosts = redisMasterHost.Split(',');
                readHosts = redisSlaveHost.Split(',');

if (readHosts.Length > 0)
                {
                    pool = new PooledRedisClientManager(writeHosts, readHosts,
                        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;
        }

public static IDictionary<string, T> GetAll<T>(IEnumerable<string> keys) where T : class
        {
            if (keys == null)
            {
                return null;
            }

keys = keys.Where(k => !string.IsNullOrWhiteSpace(k));

if (keys.Count() == 1)
            {
                T obj = Get<T>(keys.Single());

if (obj != null)
                {
                    return new Dictionary<string, T>() { { keys.Single(), obj } };
                }

return null;
            }

if (!keys.Any())
            {
                return null;
            }

IDictionary<string, T> dict = null;

if (pool != null)
            {
                keys.Select(s => new
                {
                    Index = Math.Abs(s.GetHashCode()) % readHosts.Length,
                    KeyName = s
                })
                .GroupBy(p => p.Index)
                .Select(g =>
                {
                    try
                    {
                        using (var r = pool.GetClient(g.Key))
                        {
                            if (r != null)
                            {
                                r.SendTimeout = 1000;
                                return r.GetAll<T>(g.Select(p => p.KeyName));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "获取", keys.Aggregate((a, b) => a + "," + b));
                    }
                    return null;
                })
                .Where(x => x != null)
                .ForEach(d =>
                {
                    d.ForEach(x =>
                    {
                        if (dict == null || !dict.Keys.Contains(x.Key))
                        {
                            if (dict == null)
                            {
                                dict = new Dictionary<string, T>();
                            }
                            dict.Add(x);
                        }
                    });
                });
            }

IEnumerable<Tuple<string, T>> result = null;

if (dict != null)
            {
                result = dict.Select(d => new Tuple<string, T>(d.Key, d.Value));
            }
            else
            {
                result = keys.Select(key => new Tuple<string, T>(key, Get<T>(key)));
            }

return result
                .Select(d => new Tuple<string[], T>(d.Item1.Split('_'), d.Item2))
                .Where(d => d.Item1.Length >= 2)
                .ToDictionary(x => x.Item1[1], x => x.Item2);
        }
    }
}

C# redis使用之ServiceStack的更多相关文章

  1. Redis分布式锁(ServiceStack.Redis实现)

    1.设计思路 由于Redis是单线程模型,命令操作原子性,所以利用这个特性可以很容易的实现分布式锁.A用户端在Resdis写入1个KEY,其他的用户无法写入这个KEY,实现锁的效果.A用户使用完成后释 ...

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

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

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

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

  4. ServiceStack.Redis 使用

    Redis官网提供了很多开源的C#客户端.例如,Nhiredis ,ServiceStack.Redis ,StackExchange.Redis等.其中ServiceStack.Redis应该算是比 ...

  5. ASP.NET MVC 学习笔记-2.Razor语法 ASP.NET MVC 学习笔记-1.ASP.NET MVC 基础 反射的具体应用 策略模式的具体应用 责任链模式的具体应用 ServiceStack.Redis订阅发布服务的调用 C#读取XML文件的基类实现

    ASP.NET MVC 学习笔记-2.Razor语法   1.         表达式 表达式必须跟在“@”符号之后, 2.         代码块 代码块必须位于“@{}”中,并且每行代码必须以“: ...

  6. 责任链模式的具体应用 ServiceStack.Redis订阅发布服务的调用

    责任链模式的具体应用   1.业务场景 生产车间中使用的条码扫描,往往一把扫描枪需要扫描不同的条码来处理不同的业务逻辑,比如,扫描投入料工位条码.扫描投入料条码.扫描产出工装条码等,每种类型的条码位数 ...

  7. 使用ServiceStack构建Web服务

    提到构建WebService服务,大家肯定第一个想到的是使用WCF,因为简单快捷嘛.首先要说明的是,本人对WCF不太了解,但是想快速建立一个WebService,于是看到了MSDN上的这一篇文章 Bu ...

  8. ASP.NET Redis 开发

    文件并发(日志处理)--队列--Redis+Log4Net Redis简介 Redis是一个开源的,使用C语言编写,面向“键/值”对类型数据的分布式NoSQL数据库系统,特点是高性能,持久存储,适应高 ...

  9. StackExchange.Redis通用封装类分享(转)

    阅读目录 ConnectionMultiplexer 封装 RedisHelper 通用操作类封 String类型的封装 List类型的封装 Hash类型的封装 SortedSet 类型的封装 key ...

随机推荐

  1. mac安装redis

    1.到官网下载最新的redis. http://redis.io/download 2.将下载下来的tar.gz 压缩包,(在/Users/***/Downloads)拷贝到usr/local目录下 ...

  2. 7张图片学习VIM教程

    7张图片学习VIM教程 张图片设置为桌面背景,时不时的能看上一眼.慢慢就学会VIM了. VIM lesson 1 VIM lesson 2 VIM lesson 3 VIM lesson 4 VIM ...

  3. JavaScript 正则表达式上——基本语法

    定义 JavaScript种正则表达式有两种定义方式,定义一个匹配类似 <%XXX%> 的字符串 1. 构造函数 var reg=new RegExp('<%[^%>]+%&g ...

  4. Redis数据库的使用场景介绍(避免误用Redis)

    转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/122.html?1455854235 Redis 是目前 NoSQL 领域 ...

  5. [Java集合] 彻底搞懂HashMap,HashTable,ConcurrentHashMap之关联.

    注: 今天看到的一篇讲hashMap,hashTable,concurrentHashMap很透彻的一篇文章, 感谢原作者的分享. 原文地址: http://blog.csdn.net/zhanger ...

  6. [Spring框架]Spring AOP基础入门总结二:Spring基于AspectJ的AOP的开发.

    前言: 在上一篇中: [Spring框架]Spring AOP基础入门总结一. 中 我们已经知道了一个Spring AOP程序是如何开发的, 在这里呢我们将基于AspectJ来进行AOP 的总结和学习 ...

  7. fir.im Weekly - iOS9 适配开发教程

    期待已久的 iOS 9 发布了,很多人更新完毕得出结论:这是值得升级的版本.随之而来的是适应 iOS9 开发技术.本期 Weekly 收集了一些关于 iOS9 相关的开发资源,希望对你有帮助. iOS ...

  8. spring 学习

    一.spring框架介绍 Spring 是一个开源框架,是为了解决企业应用程序开发复杂性而创建的.框架的主要优势之一就是其分层架构,分层架构允许您选择使用哪一个组件,同时为 J2EE 应用程序开发提供 ...

  9. ajax获取json对象

    ajax获取json对象 ajax获取json数据,都是一个原理,设置response 的Content-Type:application/json,这样浏览器自动会解析为json对象 $result ...

  10. Ztree行政地区树状展示

    Ztree行政地区树状展示(点击加载) 效果如下: 开始贴代码: 实体类 Item,用于对Ztree的节点展示 public class Item { private String id; priva ...