quanchinhong
quanchinhong

Reputation: 160

How to publish a message to a Redis Channel (StackExchange.Redis)

I have read an example about subscribing and publishing in StackExchange.Redis documents but I don't understand it.

Why the example doesn't talk about publishing?

var channel = multiplexer.GetSubscriber().Subscribe("messages");
channel.OnMessage(message =>
{
    Console.WriteLine((string)message.Message);
});

How to implement subscribe and publish in Dotnet Core project?

What is the RedisChannel, Anyone can explain it?

I Do like this:

RedisChannel channelWithLiteral = new RedisChannel("messages", RedisChannel.PatternMode.Literal);

And

RedisChannel channelWithLiteral = new RedisChannel("messages", RedisChannel.PatternMode.Literal);

var sub = connectionPoolManager.GetConnection().GetSubscriber();
sub.PublishAsync(channelWithLiteral , Serializer.Serialize(message));

both Sub and Pub project. Is this correct?

Upvotes: 1

Views: 5700

Answers (1)

wiki
wiki

Reputation: 2033

After adding Redis package to your project (via StackExchange.Redis NuGet package), you can connect to your Redis server (in this case, local):

using StackExchange.Redis;

ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("localhost");

Next, you should subscribe to a channel using the ISubscriber.Subscribe:

var subscriber = connection.GetSubscriber();

Publishing messages to any channel can be done with:

subscriber.Publish("channle-name", "This is a message");

And finally, subscribing to the same channel (from another client maybe) to receive messages sent over your desired channel:

subscriber.Subscribe("channle-name", (channel, message) => {
    Console.WriteLine((string)message);
});

Upvotes: 5

Related Questions