RabbitMQ消费者接收Message乱码问题

问题描述:

使用Message来提取具体得消息内容时出现部分数据乱码的现象,byte[]数组用utf-8编码仍然无效

@Override
    public void onMessage(Message message, Channel channel) throws Exception
     {
          
   
            String result = new String(message.getBody(),"utf-8");
            System.out.println(result);
            JSONObject jsonObject = JSONObject.parseObject(result);
     }

解决方法:

原因:发送时消息没有序列化。
解决方法:1.对实体类进行序列化(实体类情况下)
				  2.因为我使用的是Map作为消息,所以我选择将它转化为json字符串进行传输
@GetMapping("/sendDirectMessage")
    public String sendDirectMessage() {
          
   
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "test message, 你好!!!";
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String,Object> map=new HashMap<>();
        map.put("messageId",messageId);
        map.put("messageData",messageData);
        map.put("createTime",createTime);

        System.out.println("发送时打印消息内容:"+messageId);
        //将消息携带绑定键值:TestDirectRouting 发送到交换机TestDirectExchange
        rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting", JSONObject.toJSONString(map),new CorrelationData(messageId));
        return "ok";
    }

运行结果:没有乱码 并且以json格式出现

经验分享 程序员 微信小程序 职场和发展