Redis總結(三)Redis 的主從復制,redis總結主從復制
接著上一篇,前面兩篇我總結了《Redis總結(一)Redis安裝》和《Redis總結(二)C#中如何使用redis》 所以這一篇,會講講Redis 的主從復制以及C#中如何調用。
Redis跟MySQL一樣,擁有非常強大的主從復制功能,而且還支持一個master可以擁有多個slave,而一個slave又可以擁有多個slave,從而形成強大的多級服務器集群架構。

redis的主從復制是異步進行的,它不會影響master的運行,所以不會降低redis的處理性能。主從架構中,可以考慮關閉Master的數據持久化功能,只讓Slave進行持久化,這樣可以提高主服務器的處理性能。同時Slave為只讀模式,這樣可以避免Slave緩存的數據被誤修改。
1.配置
實際生產中,主從架構是在幾個不同服務器上安裝相應的Redis服務。為了測試方便,我這邊的主從備份的配置,都是在我Windows 本機上測試。
1. 安裝兩個Redis 實例,Master和Slave。 具體Redis安裝步驟,請參考前一篇博文 《Redis總結(一)Redis安裝》。

2. 將Master端口設置為6379,Slave 端口設置為6380 。bind 都設置為:127.0.0.1。在Slave 實例 ,增加:slaveof 127.0.0.1 6379 配置。 配置完成之後,啟動這兩個實例,如果輸出如下內容,說明主從復制的架構已經配置成功了。
注意:在同一台電腦上測試,Master和Slave的端口不要一樣,否則是不能同時啟動兩個實例的。
2.測試
在命令行,分別連接上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);
}
}
}
View Code