使用java springboot 使用 Redis 作为消息队列

使用 Redis 作为消息队列

Redis 还可以用作消息队列,特别是通过其发布/订阅(Pub/Sub)机制。你可以使用 RedisTemplate 的 convertAndSend 方法发送消息,并使用 @RedisListener 注解监听消息。

发送消息
复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class MessagePublisher {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void publishMessage(String channel, String message) {
        redisTemplate.convertAndSend(channel, message);
    }
}
监听消息
复制代码
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Service;

@Service
public class MessageSubscriber {

    @Autowired
    private RedisMessageListenerContainer redisContainer;

    public void subscribeToChannel(String channel) {
        ChannelTopic topic = new ChannelTopic(channel);
        redisContainer.addMessageListener((message, pattern) -> {
            System.out.println("Received message: " + message.toString());
        }, topic);
    }
}
相关推荐
叫个啥呢26 分钟前
第一次写 DSH 插件:跟着自己的喜好实现个简单的代码管理插件
前端
掘金酱38 分钟前
AI 带来的新生意|稀土掘金 X-Lab 年度大会招募开启
前端·后端·vibecoding
某哈压力大40 分钟前
移动端 rem 适配
前端·vue.js·面试
泯泷1 小时前
Vercel AI SDK 6 完整教程系列 - 第一部分:基础入门篇
前端·javascript
lcy_241 小时前
10 万条数据滚动不卡?聊聊我写的虚拟列表组件 vue-virtualize
前端
zhanlang02171 小时前
HTML 零基础入门到企业实战【第七章 7.5】表单验证基础属性:required、maxlength、placeholder
前端·html
涛涛ing1 小时前
为了快 30 倍,我把构建工具换成了 Rust,结果团队差点连班都加不了
前端
parade岁月2 小时前
SolidJS 2.0 正式发布:异步成为响应式的一部分
前端
lcy_242 小时前
防抖节流、并发控制、指数退避重试——我把它收进了一个库 async-concurrency-kit
前端