帮我写出springboot整合redis实现发布订阅的详细代码
时间: 2024-09-19 12:08:19 浏览: 44
在Spring Boot项目中整合Redis实现发布订阅功能,你需要使用`lettuce`或`spring-data-redis`库来操作Redis,并利用其内置的pub/sub功能。这里是一个简单的例子,首先确保你已经在pom.xml文件中添加了相应的依赖:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-redis</artifactId>
</dependency>
</dependencies>
```
然后创建一个RedisTemplate配置类,设置连接池:
```java
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.PubSubMessage;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
public class RedisConfig {
@Bean
public RedisConnectionFactory redisConnectionFactory() {
// 这里填写你的Redis连接配置,如 host、port 等
return new LettuceConnectionFactory("localhost", 6379);
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 如果需要序列化/反序列化数据,可以设置序列化策略
// template.setKeySerializer(new StringRedisSerializer());
// template.setValueSerializer(new GenericToStringSerializer<>(Object.class));
return template;
}
@Bean
public RedisMessageListenerContainer messageListenerContainer(RedisTemplate<String, Object> template) {
MessageListenerAdapter adapter = new MessageListenerAdapter(
(PubSubMessage<String, String> message) -> handleSubscribeMessage(message),
"subscribeChannel");
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(template.getConnectionFactory());
container.addMessageListener(adapter, new ChannelTopic<>("publishChannel"));
return container;
}
private void handleSubscribeMessage(PubSubMessage<String, String> message) {
System.out.println("Received message on subscribe channel: " + message.getMessage());
// 这里处理接收到的消息,例如存储到其他地方或转发给其他服务
}
}
```
最后,在`handleSubscribeMessage`方法中,你可以编写处理接收消息的逻辑。当有新的消息发布到`"publishChannel"`时,所有订阅该频道的客户端都会收到通知。
阅读全文