Spring Boot 整合Redis实现消息发布与订阅
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.stereotype.Component;
@Component
public class RedisPubSub {
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private ChannelTopic topic;
public void publish(String message) {
redisTemplate.convertAndSend(topic.getTopic(), message);
}
public void subscribe(RedisMessageListener listener) {
redisTemplate.executeSubscribe(listener);
}
}
// 消息监听器示例
public class RedisMessageListener implements MessageListener {
@Override
public void onMessage(Message message, byte[] pattern) {
// 处理接收到的消息
String receivedMessage = new String(message.getBody(), StandardCharsets.UTF_8);
System.out.println("Received Redis message: " + receivedMessage);
}
}
这个代码示例展示了如何在Spring Boot应用程序中使用StringRedisTemplate
发送消息和订阅通道。RedisPubSub
类中定义了发布和订阅方法,RedisMessageListener
是一个简单的消息监听器示例,用于处理接收到的消息。
评论已关闭