StackService.Redis Pub/Sub应用实例

新建项目后先引用库ServiceStack.Redis


1. 参数配置

/* 连接字符串格式
 * localhost
 * 127.0.0.1:6379
 * redis://localhost:6379
 * password@localhost:6379
 * clientid:password@localhost:6379
 * redis://clientid:password@localhost:6380?ssl=true&db=1
 */
var redis_servre = "192.168.1.104:6379";
var redis_channel = "test@#";
var channel_exit = "exit";

2. 建立redis连接池

var rwHosts = new string[] { redis_servre };
var rHosts = new string[] { };
var redisPool = new PooledRedisClientManager(rwHosts, rHosts, new RedisClientManagerConfig()
{
    MaxWritePoolSize = 5,
    MaxReadPoolSize = 5,
    AutoStart = true
});

3. 订阅channels

var t_sub = new Thread(() =>
{
    //using (var redisClient = new RedisClient("192.168.1.104", 6379))
    using (var redisClient = redisPool.GetClient())
    {
        using (var sub = redisClient.CreateSubscription())
        {
            sub.OnMessage = (channel, msg) =>
            {
                Console.WriteLine("recv {0} from {1}", msg, channel);
                if (msg == channel_exit)
                {
                    sub.UnSubscribeFromAllChannels();
                }
            };
            //会阻塞线程
            sub.SubscribeToChannels(redis_channel);
        }
    }
    Console.WriteLine("sub exit");
});
t_sub.Start();

4. 向channel发布消息

using (var redisClient = redisPool.GetClient())
{
    redisClient.PublishMessage(redis_channel, "hello");
    Console.ReadKey();
    redisClient.PublishMessage(redis_channel, channel_exit);
}

5. 运行程序查看效果,可以通过redis-cli程序发送消息试试看

>publish test@# hello
>publish test@# exit


你可能感兴趣的:(redis,C#,subscribe,publish)