使用redis进行消息推送

  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);
    }
}

 

posted @ 2015-04-21 10:02  silent  阅读(6643)  评论(0编辑  收藏  举报