2

Through the previous centralized cache usage tutorial , we have learned about the core function of Redis: as a high-performance cache for K and V storage.

Next, we will divide into several articles to continue to talk about some other powerful uses of Redis! If you are interested in this, be sure to pay attention to collect me!

Publish and subscribe model

If you have read the related MQ article I wrote before, then you should not be unfamiliar with the publish and subscribe function. If you haven't read it, it doesn't matter. Here is a brief introduction. If you already know, you can skip to the next section.

What is the publish-subscribe model?

There is an important role in the publish-and-subscribe model, one is the Publisher, and the other is the Subscriber. In essence, the publish-subscribe model is a producer-consumer model. Publisher is responsible for producing messages, while Subscriber is responsible for consuming the messages it subscribes to. This mode is widely used in the design of software and hardware systems. For example, after a configuration of the configuration center is modified, it is delivered to subscribers subscribing to this configuration by way of publish and subscribe to realize automatic refresh.

observer mode?

Seeing this, 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 the publish-subscribe pattern and the two concepts in the observer pattern seem to be doing something. The same thing? So: Publisher is the Subject in the observer mode? Subscriber is the Observer in the observer pattern?

important difference between 160e00af92ddc4?

The role tasks of these two modes are indeed very similar, but there is a core difference in terms of implementation architecture!

We understand through the following diagram, it is very clear:

观察者模式

发布订阅模式

You can see that there is a very big difference here: publish-subscribe mode is an intermediate role to transition between the two roles, the publisher does not directly interact with the subscriber .

Recall the producer-consumer model. This intermediate transition area corresponds to the buffer zone. Because of the existence of this buffer, the work of publishers and subscribers can be decoupled to a greater degree. Publishers will not affect their own publishing tasks because of the slow processing speed of subscribers. It only needs to produce quickly. And subscribers don't have to worry too much about being too late to deal with it, because there is a buffer zone, which can be done in a little bit of queue (that is, the effect of "peak cutting and filling valley" we often call).

The essence of the well-known middleware such as RabbitMQ, Kafka, and RocketMQ is actually to implement this intermediate buffer in the publish-subscribe model. And Redis also provides a simple publish and subscribe implementation, which can be used when we have some simple needs! If you already understand this concept, then go to the next section and let's make an example together!

Give it a try

For the following hands-on tasks, we will implement the role of a message publisher in the Spring Boot application through an interface, and then write a Service to implement message subscription (print the message content passed by the interface).

first step : Create a basic Spring Boot application, if you don’t yet 160e00af932334 click here

second step : add several 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>

third step : Create an interface 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) {
            // 发送消息
            redisTemplate.convertAndSend(CHANNEL, message);
        }

    }

}

For the sake of simple implementation, I wrote the public CHANNEL name field in the main application class.

Fourth step : Continue to implement message subscription in the main class of the application, and 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) {
                    // 收到消息的处理逻辑
                    log.info("Receive message : " + message);
                }
            }, CHANNEL.getBytes(StandardCharsets.UTF_8));

        }

    }

Step 6 : Verification result

  1. Start the application Spring Boot main class
  2. curl localhost:8080/publish?message=hello through curl or other tools
  3. Observe the console, you can see that the received message parameters are printed
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's content. If you are interested in this series of tutorials "Spring Boot 2.x Basic Tutorial", you can directly! . If you encounter difficulties in the learning process, it is recommended to join Spring technical exchange group , participate in exchanges and discussions, and better study and progress!

Code example

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

If you think this article is good, welcome Star support, your attention is my motivation for persistence! More free tutorials in this series "Click to enter the summary catalog"

Welcome to pay attention to my public account: Program Ape DD, share knowledge and thoughts that can’t be seen elsewhere

程序猿DD
2.2k 声望2.8k 粉丝

作品:《Spring Cloud微服务实战》、SpringForAll社区、OpenWrite、Youtube中文配音