创建RedisMessagePublisher
和RedisMessageSubscriber
。RedisMessagePublisher
用于发布消息到指定的频道,而RedisMessageSubscriber
用于订阅频道并处理接收到的消息
using StackExchange.Redis;
using System;
public class RedisMessagePublisher
{
private readonly IConnectionMultiplexer _redis;
private readonly ISubscriber _subscriber;
public RedisMessagePublisher(string connectionString)
{
_redis = ConnectionMultiplexer.Connect(connectionString);
_subscriber = _redis.GetSubscriber();
}
public void PublishMessage(string channel, string message)
{
_subscriber.Publish(channel, message);
}
}
public class RedisMessageSubscriber
{
private readonly IConnectionMultiplexer _redis;
private readonly ISubscriber _subscriber;
public RedisMessageSubscriber(string connectionString)
{
_redis = ConnectionMultiplexer.Connect(connectionString);
_subscriber = _redis.GetSubscriber();
}
public void SubscribeToChannel(string channel, Action<string> messageHandler)
{
_subscriber.Subscribe(channel, (redisChannel, value) => messageHandler(value));
}
}
在发布消息时,你可以调用PublishMessage
方法,传递频道和消息内容。例如:
string redisConnectionString = "your-redis-connection-string";
string channel = "your-channel";
string message = "Hello, subscribers!";
var publisher = new RedisMessagePublisher(redisConnectionString);
publisher.PublishMessage(channel, message);
在订阅消息时,你可以调用SubscribeToChannel
方法,并提供频道和一个处理消息的回调函数。当有新消息到达时,回调函数将被触发并传递接收到的消息内容。例如:
string redisConnectionString = "your-redis-connection-string";
string channel = "your-channel";
var subscriber = new RedisMessageSubscriber(redisConnectionString);
subscriber.SubscribeToChannel(channel, (message) =>
{
Console.WriteLine("Received message: " + message);
// 在这里处理接收到的消息
});
请确保替换示例中的your-redis-connection-string
和your-channel
为实际的Redis连接字符串和频道名称。