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

使用 Redis 作为消息队列

Redis 还可以用作消息队列,特别是通过其发布/订阅(Pub/Sub)机制。你可以使用 RedisTemplateconvertAndSend 方法发送消息,并使用 @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);
    }
}
相关推荐
zh_xuan13 分钟前
个人主页左侧菜单支持分组,以及菜单显示和隐藏
前端·javascript·css
Ming_studying24 分钟前
HTML + CSS + JavaScript实现可视化JSON工具:格式化、折叠、搜索与错误定位
javascript·css·html·json·数据可视化·web工具
Emily156853598703 小时前
Emerson 1C31129G03 Analog Input Module
java·开发语言·前端·plc·emerson·1c31129g03·input module
To_OC8 小时前
面试被问了三回三栏布局,这次我终于把 BFC 那层窗户纸捅破了
前端·css·面试
To_OC9 小时前
啃完 TS 工具类型我发现:Pick 和 Omit 原来就是一层窗户纸
前端·面试·typescript
风月说与山鬼10 小时前
三、大括号语法
前端·react.js
kyriewen10 小时前
我把最常踩的8个CORS跨域报错整理了一遍——第8个去年还不存在
前端·javascript
Csvn11 小时前
🕰️ 闭包 + setTimeout 的 5 个经典陷阱:为什么定时器看到的永远不是最新的值?
前端
lilian23311 小时前
Harmony os 技术实战|拼豆制图27:用单字符编码承载 50 张 70×70 图纸
前端·数据库·华为·harmonyos