新建項目后先引用庫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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。