个人学习系列 - Spring Boot 配合 Redis 实现简单的发布订阅功能

如果只是想实现简单的发布订阅功能的话,又不想用消息队列增加系统的复杂性,我们可以选择Redis来做这个事情。

发布订阅

发布订阅模式就是一种生产者消费者模式,Publisher负责生产消息,而Subscriber则负责消费它所订阅的消息。
个人学习系列 - Spring Boot 配合 Redis 实现简单的发布订阅功能_第1张图片

pom.xml


    org.springframework.boot
    spring-boot-starter-web



    org.springframework.boot
    spring-boot-starter-data-redis



    org.apache.commons
    commons-pool2



    org.projectlombok
    lombok
    1.18.22

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 redisTemplate;

    public RedisController(RedisTemplate 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));

    }

}

测试

调用接口生产消息
image.png
控制台打印消费者收到的消息
image.png

个人博客地址

http://www.zhouzhaodong.xyz/

代码地址

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

你可能感兴趣的:(redisspringboot)