发布订阅

发布订阅模式就是一种生产者消费者模式,Publisher负责生产消息,而Subscriber则负责消费它所订阅的消息。

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:

消息生产者

/**
 * 消息生产者
 * @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);
    }

}

消息消费者

/**
 * 消息消费者
 * @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));

    }

}

测试

调用接口生产消息

控制台打印消费者收到的消息

个人博客地址

http://www.zhouzhaodong.xyz/

代码地址

https://gitee.com/zhouzhaodon...

03-05 21:57