使用redis進行訊息推送

silent發表於2015-04-21

  Redis支援這樣一種特性,你可以將資料推到某個資訊管道中,然後其它客戶端可以通過訂閱這些管道來獲取推送過來的資訊。使用Redis的Pub/Sub,接收方在某個channel註冊為一個訂閱者,然後監聽這個channel,一旦有訊息發到這個channel上則自動接收訊息, 利用這個特性可以輕易的實現訊息推送功能。

  1. 使用Rediscli測試

  客戶端A訂閱通道:

redis 127.0.0.1:6379> SUBSCRIBE channeltest

  客戶端B往該通道傳送訊息:

redis 127.0.0.1:6379> PUBLISH channeltest hello
(integer) 1
redis 127.0.0.1:6379> PUBLISH channeltest world
(integer) 1

  然後客戶端A就能獲取到推送的資訊

redis 127.0.0.1:6379> SUBSCRIBE channeltest
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channeltest"
3) (integer) 1
1) "message"
2) "channeltest"
3) "hello"
1) "message"
2) "channeltest"
3) "world"

  2. 批量訂閱測試

  客戶端A訂閱通道:

redis 127.0.0.1:6379> SUBSCRIBE channeltest*

  客戶端B往該通道傳送訊息:

redis 127.0.0.1:6379> PUBLISH channeltest1 hello
(integer) 1
redis 127.0.0.1:6379> PUBLISH channeltest2 world
(integer) 1

  然後客戶端A就能獲取到推送的資訊:

redis 127.0.0.1:6379> PSUBSCRIBE channeltest*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "channeltest*"
3) (integer) 1
1) "pmessage"
2) "channeltest*"
3) "channeltest1"
4) "hello"
1) "pmessage"
2) "channeltest*"
3) "channeltest2"
4) "world"

  3. C#客戶端實現

  客戶端使用TeamDev.Redis

class Program
{
    static void Main(string[] args)
    {
        try
        {
            RedisDataAccessProvider redisDataAccessProvider = new RedisDataAccessProvider();
            redisDataAccessProvider = new RedisDataAccessProvider();
            redisDataAccessProvider.Configuration.Host = "192.168.1.10";
            redisDataAccessProvider.Configuration.Port = 6379;
            redisDataAccessProvider.Connect();

            redisDataAccessProvider.ChannelSubscribed += new ChannelSubscribedHandler(redisDataAccessProvider_ChannelSubscribed);
            redisDataAccessProvider.MessageReceived += new MessageReceivedHandler(redisDataAccessProvider_MessageReceived);
            redisDataAccessProvider.Messaging.Subscribe("al");
            redisDataAccessProvider.Messaging.Subscribe("b1");
        }
        catch (Exception e)
        {
            Console.WriteLine("連線Redis錯誤:" + e.Message);
        }

        Console.ReadLine();
    }

    static void redisDataAccessProvider_MessageReceived(string channelname, string message)
    {
        if (channelname == "a1")
        {
            Console.WriteLine(message);
            Console.ReadKey();
        }
    }

    static void redisDataAccessProvider_ChannelSubscribed(string channelname)
    {
        Console.WriteLine(channelname);
    }
}

 

相關文章