【Redis】- 主從複製

Redis跟MySQL同樣,擁有很是強大的主從複製功能,並且還支持一個master能夠擁有多個slave,而一個slave又能夠擁有多個slave,從而造成強大的多級服務器集羣架構。
         
  redis的主從複製是異步進行的,它不會影響master的運行,因此不會下降redis的處理性能。主從架構中,能夠考慮關閉Master的數據持久化功能,只讓Slave進行持久化,這樣能夠提升主服務器的處理性能。同時Slave爲只讀模式,這樣能夠避免Slave緩存的數據被誤修改。html

  1.配置redis

    實際生產中,主從架構是在幾個不一樣服務器上安裝相應的Redis服務。爲了測試方便,我這邊的主從備份的配置,都是在我Windows 本機上測試。緩存

    1. 安裝兩個Redis 實例,Master和Slave。將Master端口設置爲6379,Slave 端口設置爲6380 。bind 都設置爲:127.0.0.1。 服務器

    

    2. 在Slave 實例 ,增長:slaveof 127.0.0.1 6379 配置。以下圖所示:session

    

 

    配置完成以後,啓動這兩個實例,若是輸出以下內容,說明主從複製的架構已經配置成功了。架構

    

 

    注意:在同一臺電腦上測試,Master和Slave的端口不要同樣,不然是不能同時啓動兩個實例的。併發

  2.測試app

    在命令行,分別鏈接上Master服務器和Slave 服務器。而後在Master 寫入緩存,而後在Slave 中讀取。以下圖所示:異步

     
 

    3.C#中調用性能

    主從架構的Redis的讀寫其實和單臺Redis 的讀寫差很少,只是部分配置和讀取區分了主從,若是不清楚C#中如何使用redis,請參考我這篇文章 《Redis總結(二)C#中如何使用redis》。

    須要注意的是: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);
        }
    }
}

轉自:https://www.cnblogs.com/zhangweizhong/p/4980639.html