美文网首页
记一次 MQ 消息消费失败的问题

记一次 MQ 消息消费失败的问题

作者: 雁过留声_泪落无痕 | 来源:发表于2024-01-03 16:29 被阅读0次

报错

2024-01-03 00:02:40.802 [messageContainer-18] ERROR com.cmcc.edu.zhaopin.common.utils.FastJsonConvert#convertJSONToArray:71 -com.alibaba.fastjson.JSONException: field null expect '[', but string, pos 15463, line 1, column 15464"xxx"
    at com.alibaba.fastjson.parser.DefaultJSONParser.parseArray(DefaultJSONParser.java:738)
    at com.alibaba.fastjson.parser.DefaultJSONParser.parseArray(DefaultJSONParser.java:726)
    at com.alibaba.fastjson.parser.DefaultJSONParser.parseArray(DefaultJSONParser.java:721)
    at com.alibaba.fastjson.JSON.parseArray(JSON.java:643)
    at com.alibaba.fastjson.JSON.parseArray(JSON.java:623)

背景

  1. 往 mq 写消息
public void toMq(List<Xxx> list) {
    LogUtils.info(JSONObject.toJSONString(list));
    rabbitTemplate.convertAndSend("routingKey", JSONObject.toJSONString(list));
}
  1. 从 mq 取消息
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cachingConnectionFactory);
container.setMessageListener((ChannelAwareMessageListener) (message, channel) -> {
    byte[] body = message.getBody();
    String msg = new String(body);
    JSON.parseArray(msg, Xxx.class)
});

问题

从 mq 取出消息后,进行 JSON.parseArray(msg, Xxx.class) 时报了上面提到的错误,仔细一看,是取出来的字符串被转义了,导致解析成 Xxx 数组对象时失败了。

原始字符串:
[{"answerUuid":"[]","correctOrder":"[]","creatorId":2568,"paperId":1117,"questionType":1,"questionUuid":"1701414808637100","roomId":2495}]

转义后的字符串:
[{\"answerUuid\":\"[]\",\"correctOrder\":\"[]\",\"creatorId\":2568,\"paperId\":1117,\"questionType\":1,\"questionUuid\":\"1701414808637100\",\"roomId\":2495}]

分析

现在的问题,就变成了查看为何会导致字符串被转义的问题了。取出时是直接取的 Message 的 body 对象(byte 数组),肯定是没问题的;那么就只可能在写入时就被转义了。

带着这个疑问,跟着源码分析写入过程。注意到会有一个 MessageConverter 对象对传入的 Object 对象就行转换,其默认实现为 SimpleMessageConverter

protected Message createMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
    byte[] bytes = null;
    if (object instanceof byte[]) {
        bytes = (byte[])((byte[])object);
        messageProperties.setContentType("application/octet-stream");
    } else if (object instanceof String) {
        try {
            bytes = ((String)object).getBytes(this.defaultCharset);
        } catch (UnsupportedEncodingException var6) {
            throw new MessageConversionException("failed to convert to Message content", var6);
        }

        messageProperties.setContentType("text/plain");
        messageProperties.setContentEncoding(this.defaultCharset);
    } else if (object instanceof Serializable) {
        try {
            bytes = SerializationUtils.serialize(object);
        } catch (IllegalArgumentException var5) {
            throw new MessageConversionException("failed to convert to serialized Message content", var5);
        }

        messageProperties.setContentType("application/x-java-serialized-object");
    }

    if (bytes != null) {
        messageProperties.setContentLength((long)bytes.length);
        return new Message(bytes, messageProperties);
    } else {
        throw new IllegalArgumentException(this.getClass().getSimpleName() + " only supports String, byte[] and Serializable payloads, received: " + object.getClass().getName());
    }
}

可以看到,当 object 是 bytes[] 对象时,没做额外处理;是 String 对象时,直接转换位 String 对象并调用 getBytes 方法,按理说也不会有任何问题才对啊。

继续查看代码,突然发现 RabbitmqConfig.java 中提供了 RabbitTemplate 的 Bean 对象依赖。

@Bean
public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) {
    RabbitTemplate rabbitTemplate = new RabbitTemplate();
    rabbitTemplate.setConnectionFactory(connectionFactory);
    rabbitTemplate.setMessageConverter(integrationEventMessageConverter());

    ...
    return rabbitTemplate;
}

public MessageConverter integrationEventMessageConverter() {
    return new Jackson2JsonMessageConverter();
}

而在其中就指定了使用 Jackson2JsonMessageConverter 这个转换器,所以就不会走到 SimpleMessageConverter 这个转换器了。

那么问题其实也就迎刃而解了,就是 Jackson2JsonMessageConverter 这个转换器导致的,因为我们传入的是先转换为了 json 的字符串(JSONObject.toJSONString(list)),而 Jackson2JsonMessageConverter 内部又会对这个字符串进行一次 json 化处理,导致字符串会被转义一次。

其实,这也算是使用失误导致的,既然提供了 Jackson2JsonMessageConverter 这个转换器,那就不需要提前进行 json 转换了,而是直接传对象就好了,否则就会造成二次转换。

解决

方案1:
去掉 Jackson2JsonMessageConverter 这个转换器的配置,这样会默认使用 SimpleMessageConverter 这个转换器,其遇到 String 对象会直接读取其 bytes 数组

方案2:
手动 json 化对象(JSONObject.toJSONString(list)),然后手动构造 Message 对象

List<Xxx> list = new ArrayList<>();
String json = JSONObject.toJSONString(list);
rabbitTemplate.convertAndSend("routingKey", new Message(json.getBytes(), new MessageProperties()));

方案3:
使用 Jackson2JsonMessageConverter 这个转换器,直接传入对象

List<Xxx> list = new ArrayList<>();
rabbitTemplate.convertAndSend("routingKey", list);

相关文章

网友评论

      本文标题:记一次 MQ 消息消费失败的问题

      本文链接:https://www.haomeiwen.com/subject/ikxvndtx.html