使用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);
    }
}
相关推荐
冰暮流星6 小时前
css新增盒子属性——尺寸调节
前端·css
程序员爱钓鱼6 小时前
Python编程实战 - 函数与模块化编程 - 函数的定义与调用
前端·后端·python
欧阳码农6 小时前
使用AI生成的页面总是被一眼认出来怎么办?1分钟给你解决
前端·后端
IT_陈寒6 小时前
7个鲜为人知的JavaScript性能优化技巧,让你的应用提速50%!
前端·人工智能·后端
艾小码6 小时前
前端别再乱存数据了!这3种存储方案让你的应用快如闪电
前端·javascript
黄毛火烧雪下6 小时前
HTML 的底层原理
前端·html
Moment6 小时前
面经分享——字节前端一面
前端·javascript·面试
十步杀一人_千里不留行8 小时前
Google 登录集成教程(Web + Expo 移动端)
前端
gAlAxy...11 小时前
IntelliJ IDEA 四种项目构建:从普通 Java 到 Maven Web 项目
前端·firefox
my一阁11 小时前
2025-web集群-问题总结
前端·arm开发·数据库·nginx·负载均衡·web