之前有介紹過[料理佳餚] C# StackExchange.Redis 使用 Redis Message Broker 服務,StackExchange.Redis 稍嫌美中不足,以目前來講 Failover 要自己控制,當然自己控制是沒有什麼問題的,不過既然有其他工具可以幫我們 handle 這一切,當然就讓工具來協助我們。
從 NuGet 上安裝 ServiceStack.Redis
在 NuGet 套件上直接搜尋 Redis,選到 C# Redis client for the Redis NoSQL DB 安裝即可。

建立 Redis 連線
宣告一個 PooledRedisClientManager 給入一或多個可提供 read/write 的 Redis host,在多載的方法裡面也可以給入 readOnly 的 Redis host。
再來,如果我們有配置 redundancy,就可以使用 FailoverTo() 這個方法給入 redundancy 的 host。
private IRedisClient CreateRedisClient()
{
    var redisClientManager = new PooledRedisClientManager("127.0.0.1:6379");
    redisClientManager.FailoverTo("127.0.0.1:6380");
    return redisClientManager.GetClient();
}
快取資料並指定過期時間
private void SetCache(string key, string value)
{
    // 快取 Key 為 "hello",Value 為 "world" 的資料,而且 10 秒後過期。
    this.redisClient.As<string>().SetValue(key, value, TimeSpan.FromSeconds(10));
}
取得快取資料
private string GetCache(string key)
{
    // 取得 Key 為 "hello" 的 Value。
    return this.redisClient.As<string>().GetValue(key);
}
IRedisClient.As<T>() 這個一般化的方法可以給入強型別,ServiceStack.Redis 會自動幫我們做序列化及反序列化。訂閱 Channel
private void Subscribe(string channelName)
{
    IRedisSubscription subscription = redisClient.CreateSubscription();
    // 註冊接收訊息事件
    subscription.OnMessage = (channel, msg) =>
    {
        Console.WriteLine(msg);
    };
    subscription.OnUnSubscribe = (channel) =>
    {
        Console.WriteLine("OnUnSubscribe");
    };
    Task.Run(() =>
    {
        // 由於 SubscribeToChannels 這個方法會使得 Thread 被 Blocked,
        // 因此需要將 SubscribeToChannels 放在背景執行。
        subscription.SubscribeToChannels(channelName);
    });
}
如果要取消訂閱 Channel,請參考這篇文章 Redis Pub/Sub ServiceStack, cancelling the thread。
發佈訊息到 Channel 上
private void Publish(string channelName, string message)
{
    this.redisClient.PublishMessage(channelName, message);
}
參考資料
< Source Code >
