If we just want to implement a simple publish and subscribe function, and don't want to increase the complexity of the system with message queues, we can choose Redis to do this.

publish subscribe

The publish-subscribe model is a producer-consumer model. The Publisher is responsible for producing messages, and the Subscriber is responsible for consuming the messages it subscribes to.
image.png

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>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.22</version>
</dependency>

application.yml

server:
  # 端口号配置
  port: 8080
spring:
  # redis配置
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password:

message producer

/**
 * 消息生产者
 * @author zhouzhaodong
 */
@RestController
public class RedisController {

    private final RedisTemplate<String, String> redisTemplate;

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

    @GetMapping("/publish")
    public void publish(@RequestParam String message) {
        // 发送消息
        // 下面这里需要配置发送的CHANNEL名称
        redisTemplate.convertAndSend("helloMessage", message);
    }

}

message consumer

/**
 * 消息消费者
 * @author zhouzhaodong
 */
@Slf4j
@Service
public class MessageSubscriber {

    public MessageSubscriber(RedisTemplate redisTemplate) {
        RedisConnection redisConnection = redisTemplate.getConnectionFactory().getConnection();
        redisConnection.subscribe((message, bytes) -> {
            // 收到消息的处理逻辑
            log.info("Receive message : " + message);
            // 下面这里需要配置接收的CHANNEL名称
        }, "helloMessage".getBytes(StandardCharsets.UTF_8));

    }

}

test

Call the interface to produce a message
image.png
The console prints the messages received by the consumer
image.png

Personal blog address

http://www.zhouzhaodong.xyz/

code address

https://gitee.com/zhouzhaodong/springboot/tree/master/springboot-redis-queue


周兆东
107 声望21 粉丝

一个java小白的成长之路。。。