In the previous tutorial on using the centralized cache, we saw the core functionality of Redis: a high-performance cache for K and V storage.
We will continue to talk about some other powerful uses of Redis in the next few articles! If you are interested in this, be sure to follow my collection oh!
Publish and subscribe model
If you’ve read my previous articles on MQ, you’ll be familiar with the publish-subscribe feature. If you haven’t, it doesn’t matter. Here’s a brief introduction. If you already know something, you can skip to the next section.
What is the publish subscribe model?
There are two important roles in the publish-subscription model, Publisher and Subscriber. In essence, the publish-subscribe model is a producer-consumer model, with Publisher producing messages and Subscriber consuming the messages to which it subscribes. This mode is widely used in the system design of hardware and software. For example, a configuration change in the configuration center is automatically refreshed by publishing subscriptions to subscribers who subscribe to the configuration.
Isn’t that the observer model?
Now, if you look at this, those of you who have studied design patterns can easily relate it to the observer pattern in design patterns, and you might think that the two concepts in publish and subscribe are doing the same thing as the two concepts in the observer pattern, right? So: Publisher is a Subject in observer mode? Subscriber is the Observer in Observer mode, right?
What are the important differences?
The role tasks of the two modes are indeed very similar, but there is one core difference in the implementation architecture!
Let’s take a look at the following diagram to make it clear:
You can see that there is a very big difference here: the publish/subscribe model is an intermediate role between the two roles, and the publisher does not interact directly with the subscriber.
If you think back to the producer-consumer model, this intermediate transition region corresponds to the buffer. Because of this buffer, the work of the publisher and subscriber can be decoupled to a greater degree. Publishers don’t have to be slow to publish because subscribers are slow, they just need to produce quickly. And subscribers don’t have to worry too much about running out of time, because there is a buffer and they can queue up to do it (the so-called “peak load filling” effect).
The essence of middleware such as RabbitMQ, Kafka and RocketMQ is to implement this intermediate buffer in the publish-and-subscribe model. Redis also provides a simple publish and subscribe implementation, when we have some simple requirements, but also can be used! If you already understand this concept, let’s move on to the next section and do an example.
Give it a try
In the following hands-on tasks, we will implement the role of a message publisher in the Spring Boot application through the interface, and then write a Service to implement the message subscription (print the message content sent by the interface).
Step 1: Create a basic Spring Boot application, if you can’t already click here
Step 2: Add the necessary dependencies to pom.xml:
<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>
Copy the code
Step 3: Create an interface for sending 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 messageredisTemplate.convertAndSend(CHANNEL, message); }}}Copy the code
For simplicity, I’ve put the public CHANNEL name field in the main application class.
Step 4: Continue to apply the main class to implement message subscription, print the received message processing
@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)); }}Copy the code
Step 6: Verify the results
- Start applying the Spring Boot main class
- Use curl or another tool to invoke interfaces
curl localhost:8080/publish? message=hello
- Looking at the console, you can see that the received Message parameter is printed
2021-06-19 16:22:30.935 INFO 34351 -- [ioEventloop-4-2].c.hapter55Application $MessageSubscribe: Receive message: helloCopy the code
Well, that’s all for today. If you are interested in the Spring Boot 2.x Basics tutorial, you can click direct! . If you encounter difficulties during the learning process, it is recommended to join the Spring Technology Exchange group to participate in the exchange and discussion, so as to better learn and progress!
Code sample
The complete project for this article can be viewed in the chapter5-5 directory in the repository below:
- Github:github.com/dyc87112/Sp…
- Gitee:gitee.com/didispace/S…
If you found this article good, welcomeStar
Support, your attention is my motivation! More free tutorials in this series”Click to go to summary directory”
Welcome to pay attention to my public account: program ape DD, share the outside can not see the dry goods and thinking!