Redis消息队列,获取message.getBody(),有乱码问题解决。

想要做一个redis的消息队列。运行时发现message.getBody()存在乱码
�� t{"env":"hw","group":"job"}

首先做了一下内容

java 复制代码
// Bean类
@Data
public class ADto{
  private String env;
  private String group;
}
java 复制代码
// controller类
@RestController
public class testController{
    @Resource
    private RedisTemplate redisTemplate;

    @ApiOperation("测试redis消息队列")
    @PostMapping("/redisTest")
    public String redisTest(@RequestBody ADto adto){
        redisTemplate.convertAndSend("REDIS_TEST_CHANNEL", JSONObject.toJSONString(adto));
        return "发送成功!";
    }
}
java 复制代码
//Service 类
@Service
public class AService{
    public void warnNotice(ADto adto){
    // 具体处理逻辑
        System.println.out("打印:" + adto.toString());
    }
}
java 复制代码
// redis监听器
@Component
public class RedisConfig {
    @Bean
    public ChannelTopic topic() {
        return new ChannelTopic("WARN_NOTICE_CHANNEL");
    }

    @Bean
    public MessageListenerAdapter messageListenerAdapter(WarnListener listener) {
        return new MessageListenerAdapter(listener);
    }

    @Bean
    public RedisMessageListenerContainer redisContainer(RedisConnectionFactory redisConnectionFactory,
                                                        MessageListenerAdapter messageListenerAdapter,
                                                        ChannelTopic topic) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        container.addMessageListener(messageListenerAdapter, topic);
        return container;
    }

@Component
public class WarnListener implements MessageListener {

    @Resource
    private AExtService AExtService;

    private final Object lock = new Object();

    @Override
    public void onMessage(Message message, byte[] pattern) {
        synchronized(lock) {
            ADto dto = JSONObject.parseObject(message.getBody(), ADto .class);
            AExtService.warnNotice(dto);
        }

    }
}

运行启动以后,代码在ADto dto = JSONObject.parseObject(message.getBody(), ADto .class);这一行,直接执行结束,打断点以后发现,message.getBody()获取到的内容,不是一个普通的json,而是有乱码的

�� t{"env":"hw","group":"job"}

解决方案:

将

@Resource

private RedisTemplate redisTemplate;

修改为

@Resource

private StringRedisTemplate stringRedisTemplate;

相关推荐
IT大白鼠4 天前
Redis 系列 · 第 01 篇——认知入门:Redis 是什么
redis·nosql
彧azz4 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
lbb 小魔仙4 天前
OpenClaw + cpolar 实战:远程 NAS、分享小游戏、RDP,再配置公网 AI 入口
数据库·人工智能·redis·oracle·prometheus
夕除4 天前
redis--018
redis
两锭子4 天前
Redis基础
redis
烟沙九洲4 天前
Redis 缓存穿透、缓存击穿、缓存雪崩
数据库·redis
字节探索4 天前
Redis 只会当缓存用?这 10 大实战场景,让你的系统快到飞起
redis·后端
于樱花森上飞舞4 天前
【Redis】哨兵详解
java·开发语言·数据库·redis
Rain的Java大神之路4 天前
如何快速上传10G文件
java·spring boot·redis·后端·mysql·spring cloud·面试
Wang's Blog4 天前
Java 接入Redis: 通用命令与键管理
java·服务器·redis