排查MQ訊息傳送和接收

oktokeep發表於2024-12-09

排查MQ訊息傳送和接收

TemplateCodeSmsMq mq = new TemplateCodeSmsMq();
        mq.setMobile(record.getMobile());
        mq.setTemplateCode("mySmsCode1");
        Map<String, Object> map = new HashMap<>();
        map.put("plateNum", "1111");
        String url = "短鏈地址";
        map.put("url", getShortUrl(url));
        mq.setParams(map);
//        String sendMsg = new Gson().toJson(mq);
//        log.info("傳送json1=" + JSON.toJSONString(mq));
//        log.info("傳送json2=" + sendMsg);

        //原因是:這個地方是物件mq,而不是json字串。
        rabbitTemplate.convertAndSend("test-exchange", "templateCode.test", mq);

報錯日誌:

Caused by: com.alibaba.fastjson.JSONException: can not cast to JSONObject.
at com.alibaba.fastjson.JSON.parseObject(JSON.java:260)
at com.common.FastJsonMessageConverter.fromMessage(FastJsonMessageConverter.java:44)

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to com.alibaba.fastjson.JSONObject
at com.alibaba.fastjson.JSON.parseObject(JSON.java:258)
... 17 common frames omitted

@Configuration
@Data
public class RabbitMQConfig {
    @Value("${spring.rabbitmq.host}")
    private String host;

    @Value("${spring.rabbitmq.port}")
    private int port;

    @Value("${spring.rabbitmq.username}")
    private String username;

    @Value("${spring.rabbitmq.password}")
    private String password;

    @Value("10")
    private String prefetchCount;

    public static final String DEFAULT_EXCHANGE = "default-order-exchange";

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPublisherConfirms(true);
        return connectionFactory;
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public RabbitTemplate orderSmsRabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        template.setMessageConverter(jsonMessageConverter());
        return template;
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        return template;
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new FastJsonMessageConverter();
    }

    @Bean
    public DirectExchange directExchange() {
        DirectExchange directExchange = new DirectExchange(RabbitMQConfig.DEFAULT_EXCHANGE, true, false);
        return directExchange;
    }

    @Bean
    @Primary
    public SimpleRabbitListenerContainerFactory orderRabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(jsonMessageConverter());
        factory.setConcurrentConsumers(Integer.valueOf(prefetchCount));
        return factory;
    }

}



import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.AbstractMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;

import java.io.UnsupportedEncodingException;
    
public class FastJsonMessageConverter extends AbstractMessageConverter {    
     private static Logger log = LoggerFactory.getLogger(FastJsonMessageConverter.class);

    public static final String DEFAULT_CHARSET = "UTF-8";

    private volatile String defaultCharset = DEFAULT_CHARSET;

    public FastJsonMessageConverter() {
        super();
    }

    public void setDefaultCharset(String defaultCharset) {
        this.defaultCharset = (defaultCharset != null) ? defaultCharset
                : DEFAULT_CHARSET;
    }

    @Override
    public Object fromMessage(Message message)
            throws MessageConversionException {
        String json = "";
        try {
            json = new String(message.getBody(), defaultCharset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject(json);
    }

    @SuppressWarnings("unchecked")
    public <T> T fromMessage(Message message, T t) {
        String json = "";
        try {
            json = new String(message.getBody(), defaultCharset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return (T) JSONObject.parseObject(json, t.getClass());
    }

    @Override
    protected Message createMessage(Object objectToConvert,
                                    MessageProperties messageProperties)
            throws MessageConversionException {
        byte[] bytes = null;
        try {
            String jsonString = JSONObject.toJSONString(objectToConvert);
            bytes = jsonString.getBytes(this.defaultCharset);
        } catch (UnsupportedEncodingException e) {
            throw new MessageConversionException(
                    "Failed to convert Message content", e);
        }
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        messageProperties.setContentEncoding(this.defaultCharset);
        if (bytes != null) {
            messageProperties.setContentLength(bytes.length);
        }
        return new Message(bytes, messageProperties);
    }
}

相關文章