使用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);
    }
}
相关推荐
IT_陈寒16 小时前
Python 3.12 新特性实战:10个性能优化技巧让你的代码快如闪电⚡
前端·人工智能·后端
Wiktok16 小时前
前后端开发Mock作用说明,mock.ts
前端·mock·vue3
冲!!16 小时前
SCSS 中的Mixins 和 Includes,%是什么意思
前端·css·scss
星语卿17 小时前
Vuetify:构建优雅Vue应用的Material Design组件库
前端·javascript·vue.js
roman_日积跬步-终至千里18 小时前
【系统架构设计(25)】Web应用服务器与现代架构
前端·架构·系统架构
yshhuang18 小时前
在Windows上搭建开发环境
前端·后端
littleplayer18 小时前
Redux在iOS中的使用
前端
跟橙姐学代码18 小时前
Python里的“管家婆”:带你玩转os库的所有神操作
前端·python·ipython