StackService.Redis Pub/Sub应用实例
新建项目后先引用库ServiceStack.Redis1. 参数配置
1
2
3
4
5
6
7
8
9
10
11
/* 连接字符串格式
* 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连接池
1
2
3
4
5
6
7
8
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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发布消息
1
2
3
4
5
6
using (var redisClient = redisPool.GetClient())
{
redisClient.PublishMessage(redis_channel, "hello");
Console.ReadKey();
redisClient.PublishMessage(redis_channel, channel_exit);
}
5. 运行程序查看效果,可以通过redis-cli程序发送消息试试看
1
2
>publish test@# hello
>publish test@# exit
页:
[1]