springbootredis的生产者和消费者
时间: 2023-10-17 17:22:14 浏览: 67
Spring Boot集成Redis可以使用RedisTemplate来实现消息的生产和消费。下面是一个简单的生产者和消费者示例:
```java
// 生产者
@Service
public class RedisMessageProducer {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void sendMessage(String channel, Object message) {
redisTemplate.convertAndSend(channel, message);
}
}
// 消费者
@Component
public class RedisMessageConsumer implements MessageListener {
@Override
public void onMessage(Message message, byte[] pattern) {
String channel = new String(message.getChannel());
String msg = new String(message.getBody());
System.out.println("Received message: " + msg + " from channel: " + channel);
}
}
// 配置
@Configuration
public class RedisConfig {
@Autowired
private RedisMessageConsumer redisMessageConsumer;
@Bean
public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnectionFactory);
container.addMessageListener(redisMessageConsumer, new PatternTopic("myChannel"));
return container;
}
}
```
生产者使用RedisTemplate的convertAndSend方法向指定的频道发送消息,而消费者则需要实现MessageListener接口,并通过RedisMessageListenerContainer来监听指定的频道。需要注意的是,在配置文件中需要定义RedisConnectionFactory来连接Redis数据库。
阅读全文