[Redis] .net core Redis event subscription and publishing, basics

2023, Week 38. Give yourself a goal, and then stick to it and you will always get something. If you don’t believe me, try it!
Publish/Subscribe (also referred to as Pub/Sub) is a messaging model used to decouple the relationship between publishers and subscribers.

Insert image description here

1. Basic concepts

Publish/Subscribe (also referred to as Pub/Sub) is a messaging model used to decouple the relationship between publishers and subscribers.

In the publish and subscribe model, the publisher (Publisher) does not directly send messages to specific subscribers (Subscriber), but publishes the messages to one or more topics (Topic). Subscribers can choose to subscribe to topics of interest. When a message is published to the subscribed topic, the subscriber will receive the corresponding message.

Key concepts:

1.1. Publisher

Responsible for publishing messages to a specific topic, regardless of the subscribers.

1.2. Topic

The category or label of the message, specify the topic when publishing the message.

1.3. Subscriber

Choose to subscribe to a topic of interest. When a message is published to the subscribed topic, the corresponding message will be received.

1.4. Message

Information sent by the publisher, containing data and metadata.

The relationship between publishers and subscribers is decoupled. The publisher does not need to know which subscribers there are, and the subscribers only need to pay attention to the topics they are interested in.
This pattern can be used to implement loosely coupled system designs, making the system easier to expand and maintain.

The publish and subscribe model is often used in asynchronous messaging, event-driven programming, message queues and other scenarios. For example, message middleware (such as RabbitMQ, Apache Kafka) is implemented based on the publish and subscribe model.

2. Simple example

It is very simple to use Redis for event subscription and publishing in .NET Core.
The following is a sample code that demonstrates how to use Redis for event publishing and subscription:

2.1. Install NuGet package

StackExchange.Redis

2.2. Create a Redis connection

var redis = ConnectionMultiplexer.Connect("localhost");
var subscriber = redis.GetSubscriber();

2.3. Release events

subscriber.Publish("channel", "message");

2.4. Subscription events

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

When a message is published to the specified channel, the subscriber will receive the message and execute the specified processing logic.

It should be noted that this is just a simple example. In actual applications, more situations may need to be considered, such as running subscribers in the background, exception handling, etc.
Additionally, you can use pattern matching (wildcards) to subscribe to multiple channels.
For more advanced usage and settings, please refer to the documentation for StackExchange.Redis.

3. Ordered set example

When using Redis for event subscription and publishing in .NET Core, if you want to record the occurrence of events, you can use one of Redis's data structures - Sorted Set (Sorted Set) to record.

Here is a sample code that demonstrates how to use a sorted collection to record the occurrence of an event:

3.1. Install NuGet package

StackExchange.Redis

3.2. Create a Redis connection

var redis = ConnectionMultiplexer.Connect("localhost");
var db = redis.GetDatabase();
var subscriber = redis.GetSubscriber();

3.3. Define the key of a record table

const string eventLogKey = "eventLog";

3.4. Release events

string message = "message";
double timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
subscriber.Publish("channel", message);

// 记录事件到有序集合中,按照时间戳排序
db.SortedSetAdd(eventLogKey, message, timestamp);

3.5. Subscription events

subscriber.Subscribe("channel", (channel, message) => {
    
    
    Console.WriteLine((string)message);
    
    // 在事件发生时,更新有序集合中的时间戳
    double timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
    db.SortedSetAdd(eventLogKey, (string)message, timestamp);
});

By using sorted collections, you can maintain a time-ordered event record table in Redis.
You can use various operations of SortedSet according to your needs, such as obtaining event records based on time range, obtaining the latest events, etc.

Please note that this is just a basic example, and more situations may need to be considered in actual applications, such as exception handling, cleaning up expired events, etc.
In addition, it is recommended to optimize the structure and data operations of the record table based on actual business needs.
For more advanced usage and settings, please refer to the documentation for StackExchange.Redis.

4. Combined with Sql Server table

To use Redis in .NET Core for event subscription and publishing, and to add event information to a SQL Server database table, you can follow the following steps:

4.1. Install NuGet package

StackExchange.Redis、Microsoft.Data.SqlClient

4.2. Create Redis connection and SQL Server connection

var redis = ConnectionMultiplexer.Connect("localhost");
var db = redis.GetDatabase();
var subscriber = redis.GetSubscriber();

string connectionString = "Your_SQL_Server_Connection_String";
using var connection = new SqlConnection(connectionString);

4.3. Create a database table to store event information

CREATE TABLE EventLog (
    Id INT IDENTITY(1,1) PRIMARY KEY,
    Channel NVARCHAR(100),
    Message NVARCHAR(MAX),
    Timestamp DATETIME
);

4.4. Release events

string message = "message";
string channel = "channel";
DateTime timestamp = DateTime.UtcNow;

subscriber.Publish(channel, message);

// 添加事件信息到 SQL Server 数据库表中
string sql = @"INSERT INTO EventLog (Channel, Message, Timestamp)
               VALUES (@Channel, @Message, @Timestamp)";
connection.Execute(sql, new {
    
     Channel = channel, Message = message, Timestamp = timestamp });

4.5. Subscription events

subscriber.Subscribe("channel", (redisChannel, message) => {
    
    
    Console.WriteLine((string)message);
    
    // 添加事件信息到 SQL Server 数据库表中
    string sql = @"INSERT INTO EventLog (Channel, Message, Timestamp)
                   VALUES (@Channel, @Message, @Timestamp)";
    connection.Execute(sql, new {
    
     Channel = redisChannel, Message = (string)message, Timestamp = DateTime.UtcNow });
});

Through the above steps, you can publish and subscribe to events in Redis, and add event information to the SQL Server database table for storage. Please perform appropriate optimization and exception handling according to your actual needs.

Guess you like

Origin blog.csdn.net/lmy_520/article/details/132802323