使用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);
    }
}
相关推荐
其实防守也摸鱼8 小时前
Cylab在线靶场——挑战图书馆初学者指南
服务器·前端·数据库·chrome·安全·网络安全·靶场
拆房老料10 小时前
【第四部分:Agentic 智能体设计模式】16. 一个 Prompt 搞不定复杂任务?试试 Prompt Chaining
java·前端·人工智能·设计模式·prompt
曹牧15 小时前
C#:空合并运算符
java·前端·数据库
小羊没烦恼!16 小时前
铁道部新客票系统设计(二)
开发语言·前端·数据库·python·oracle·c#·php
智能直播19 小时前
RK3518:1.5G 内存 + 8G 存储,如何跑起硬件编解码、Web、AI 识别、绿幕特效
前端·人工智能·5g
掘金酱20 小时前
【10.24 特别活动】AI 时代,程序员的新饭碗在哪里?
前端·人工智能·后端
excel20 小时前
多进程环境下使用 PM2 部署 Socket.IO:需要注意什么
前端
IT_陈寒20 小时前
Redis的原子性竟然失效了?记一次分布式锁翻车实录
前端·人工智能·后端
时间的情敌1 天前
《回顾 2018 前端:Vue2 成熟期,Webpack4 发布,PWA 大火》
前端
Java后端的Ai之路1 天前
前端技术Vue-09-webpack-vuejs-实战
前端·vue.js·webpack