5分钟实现springboot整合redis发布订阅功能

在Spring Boot中整合Redis的发布订阅功能,通常需要以下几个步骤:

  1. 添加依赖:在pom.xml文件中添加Spring Boot的Redis依赖。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 配置Redis:在application.propertiesapplication.yml文件中配置Redis服务器的连接信息。
# application.properties
spring.redis.host=your_redis_host
spring.redis.port=your_redis_port
spring.redis.password=your_redis_password
  1. 创建配置类:创建一个配置类来配置RedisTemplate和StringRedisTemplate,这些模板将被用于发送和接收消息。
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(lettuceConnectionFactory);
        // 设置序列化工具,这里使用Jackson2JsonRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
    @Bean
    public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        return new StringRedisTemplate(lettuceConnectionFactory);
    }
}
  1. 发布消息:使用StringRedisTemplateRedisTemplate发布消息。
@Service
public class RedisPublisher {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public void publishMessage(String topic, String message) {
        stringRedisTemplate.convertAndSend(topic, message);
    }
}
  1. 订阅消息:创建一个监听器来接收消息。
@Service
public class RedisSubscriber {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @PostConstruct
    public void init() {
        stringRedisTemplate.listen(new ChannelTopic("your_channel"), new MessageListener() {
            @Override
            public void onMessage(Message message, byte[] pattern) {
                // 处理接收到的消息
                System.out.println("Received: " + message);
            }
        });
    }
}
  1. 测试发布订阅功能:创建一个测试类或控制器来测试发布和订阅功能。
@RestController
public class PubSubController {
    @Autowired
    private RedisPublisher publisher;
    @GetMapping("/publish")
    public String publishMessage(@RequestParam String topic, @RequestParam String message) {
        publisher.publishMessage(topic, message);
        return "Message published";
    }
}

这样,当调用/publish接口时,Redis会发布消息到指定的频道(topic),而订阅了该频道的所有客户端都会收到消息。
请注意,以上代码示例可能需要根据你的具体需求进行调整。此外,确保Redis服务器已正确配置并正在运行,以便能够成功地进行发布和订阅操作。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值