// 建立 Redis 连接  发送部分代码
using StackExchange.Redis;

ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379,password=123456");

// 获取发布者
ISubscriber publisher = redis.GetSubscriber();

// 发布消息到指定频道
string channel = "channel";
string message = "Hello, Redis!";
publisher.Publish(channel, message);

Console.WriteLine($"Message '{message}' published to channel '{channel}'. Press Enter to exit.");

// 等待用户输入,以便程序不会立即退出
Console.ReadLine();

订阅者1代码

// 建立 Redis 连接
using StackExchange.Redis;

ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379,password=123456");
// 获取订阅者
ISubscriber subscriber = redis.GetSubscriber();
// 订阅符合特定模式的频道
string pattern = "channel";
subscriber.Subscribe(pattern, (channel, message) => {
    Console.WriteLine($"Received message from pattern '{pattern}': {message}");
});
Console.WriteLine($"Subscribed to pattern '{pattern}'. Press Enter to exit.");
// 等待用户输入,以便程序不会立即退出
Console.ReadLine();
// 取消订阅
subscriber.Unsubscribe(pattern);
 

订阅者2代码

// 建立 Redis 连接
using StackExchange.Redis;

ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379,password=123456");
// 获取订阅者
ISubscriber subscriber = redis.GetSubscriber();
// 订阅符合特定模式的频道
string pattern = "channel";
subscriber.Subscribe(pattern, (channel, message) => {
    Console.WriteLine($"Received message from pattern '{pattern}': {message}");
});
Console.WriteLine($"Subscribed to pattern '{pattern}'. Press Enter to exit.");
// 等待用户输入,以便程序不会立即退出
Console.ReadLine();
// 取消订阅
subscriber.Unsubscribe(pattern);

发布者发送消息如下

C# redis 菜鸟级别 订阅与频道,发送消息-LMLPHP

02-21 12:48