【Java】SpringBoot中实现Redis Stream队列
在Spring Boot中实现Redis Stream队列,你可以使用spring-boot-starter-data-redis
依赖,并利用StreamReceiver
来接收消息。以下是一个简单的例子:
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 配置Redis Stream:
@Configuration
public class RedisStreamConfig {
@Autowired
private RedisConnectionFactory connectionFactory;
@Bean
public StreamListener streamListener() {
return new StreamListener();
}
@Bean
public StreamReceiver streamReceiver() {
return new StreamReceiver();
}
@Bean
public StreamTemplate streamTemplate() {
return new StreamTemplate(connectionFactory, "myStreamKey");
}
}
- 创建
StreamListener
来监听Redis Stream:
public class StreamListener {
@Autowired
private StreamReceiver streamReceiver;
@StreamListener(target = "myStreamKey")
public void receive(Message<String, Map<String, Object>> message) {
streamReceiver.receiveMessage(message);
}
}
- 实现
StreamReceiver
来处理接收到的消息:
public class StreamReceiver {
public void receiveMessage(Message<String, Map<String, Object>> message) {
// 处理消息逻辑
System.out.println("Received message: " + message.toString());
}
}
确保你的Redis服务器已启用并运行,并且配置了正确的连接信息。这样,当有消息发送到myStreamKey
时,StreamReceiver
的receiveMessage
方法会被调用,并处理接收到的消息。
评论已关闭