Spring boot 2. X basic tutorial: using redis's publish subscribe function
Program description DD 2021-06-25 01:51:58

Pass the previous one Tutorial on the use of centralized caching , We already know Redis Core functions : As K、V High performance cache for storage .

Next, we will continue to talk about it in several chapters Redis Some other powerful uses of ! If you're interested , You must pay attention to me !

Publish subscribe mode

If you read what I wrote before About MQ Related articles of , So the publish subscribe function should not be strange . If I haven't seen , It doesn't matter , Here is a brief introduction , You can skip what you already know and go straight to the next section .

What is publish and subscribe mode ?

It plays an important role in the publish subscribe model , One is the publisher Publisher, Another subscriber Subscriber. In essence , The publish subscribe model is a producer consumer model ,Publisher Responsible for production information , and Subscriber Is responsible for consuming the messages it subscribes to . This mode is widely used in software and hardware system design . such as : After a configuration change in the configuration center , It is delivered to subscribers who subscribe to this configuration through publish subscribe to realize automatic refresh .

It's the observer model ?

See here , Students who have studied design patterns may easily associate it with the observer pattern in design patterns , You will feel that the two concepts in publish subscribe mode and the two concepts in observer mode seem to do the same thing ? therefore :Publisher It's in the observer mode Subject?Subscriber It's in the observer mode Observer?

What are the important differences ?

The roles and tasks of these two modes are very similar , But there is a core difference in the implementation architecture !

Let's understand it through the following diagram , It's clear :

 Observer mode

 Publish subscribe mode

As you can see, there is a very big difference here : Publish subscribe mode is a transition between two roles , Publishers don't interact directly with subscribers .

Think back to the producer consumer model , This intermediate transition area corresponds to a buffer . Because of this buffer , The work of publishers and subscribers can be decoupled to a greater extent . Publishers don't have to be slow by subscribers , And affect their own release tasks , It just needs to be produced quickly . And subscribers don't have to worry too much about not having time to deal with it , Because there are buffers in , You can line up a little bit ( That's what we often say “ Peak shaving and valley filling ” effect ).

And what we know RabbitMQ、Kafka、RocketMQ The essence of these middleware is to implement the intermediate buffer in publish subscribe mode . and Redis It also provides a simple publish subscribe implementation , When we have some simple needs , It can also be used ! If you already understand the concept , So let's move on to the next section , Let's make an example !

Give it a try

The following hands-on tasks , We will be in Spring Boot Application , Realize the role of a message publisher through the interface , And then another one Service To subscribe to messages ( Print the message from the interface ).

First step : Create a basic Spring Boot application , If not yet Click here

The second step pom.xml Add a few necessary dependencies to :

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>

The third step : Create an interface , Used to send messages .

@SpringBootApplication
public class Chapter55Application {

private static String CHANNEL = "didispace";

public static void main(String[] args) {
SpringApplication.run(Chapter55Application.class, args);
}

@RestController
static class RedisController {

private RedisTemplate<String, String> redisTemplate;

public RedisController(RedisTemplate<String, String> redisTemplate) {
this.redisTemplate = redisTemplate;
}

@GetMapping("/publish")
public void publish(@RequestParam String message) {
// Send a message
redisTemplate.convertAndSend(CHANNEL, message);
}

}

}

Here for simple implementation , public CHANNEL Name field , I wrote it all in the main application class .

Step four : Continue to implement message subscription in the main class , Print the received message

@Slf4j
@Service
static class MessageSubscriber {

public MessageSubscriber(RedisTemplate redisTemplate) {
RedisConnection redisConnection = redisTemplate.getConnectionFactory().getConnection();
redisConnection.subscribe(new MessageListener() {
@Override
public void onMessage(Message message, byte[] bytes) {
// The processing logic of the received message
log.info("Receive message : " + message);
}
}, CHANNEL.getBytes(StandardCharsets.UTF_8));

}

}

Step six : The verification results

  1. Start the application Spring Boot The main class
  2. adopt curl Or other tools to call the interface curl localhost:8080/publish?message=hello
  3. Observation console , You can see the print of the received message Parameters
2021-06-19 16:22:30.935 INFO 34351 --- [ioEventLoop-4-2] .c.Chapter55Application$MessageSubscribe : Receive message : hello

Okay , That's the end of today . If you're interested in this series of tutorials 《Spring Boot 2.x Basic course 》 Interested in , Sure Click through !. If you encounter difficulties in the process of learning , It is suggested to join Spring Technology exchange group , Participate in communication and discussion , Better learning and progress !

Code example

The complete project of this article can be found in the following warehouse chapter5-5 Catalog :

If you think this article is good , welcome Star Support , Your concern is the driving force of my persistence ! More free tutorials in this series 「 Click to enter the summary Directory 」

Please bring the original link to reprint ,thank
Similar articles