7 RabbitMQ异常:No method found for

2023-10-26  本文已影响0人  滔滔逐浪

昨天新写了个[队列],日志疯狂报“No method found for class [B”错误,日志一度干到50G。
造成该错误原因是消费者接收到了Json格式的字符串。

解决步骤

1:RabbitMqConfig添加Json格式的字符串转成字节码

@Configuration
public class RabbitMqConfig {

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        return rabbitTemplate;
    }

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        return factory;
    }
}



2 修改消费者接收参数类型

package com.yunshu.main.rabbitmq.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 创建消息接收监听类
 *
 * @autor tom
 * @date 2020/3/19 0019 15:29
 */
@Component
@RabbitListener(queues = "monitor_topic_exchange")//监听的队列消息
public class DirectReceiver {
    @RabbitHandler
    public void process(Map map) {
        System.out.println("DirectReceiver消费者收到消息:" + map.toString());
    }

    @RabbitHandler
    public void process(String testMessage) {
        System.out.println("DirectReceiver消费者收到消息:" + testMessage.toString());
    }

    @RabbitHandler
    public void process(byte[] message) {
        try {
            String messageStr = new String(message, StandardCharsets.UTF_8.name());
            // 根据自己传入类转换对应接收类型
            Map<String, Object> map = JSONObject.parseObject(messageStr, Map.class);
            System.out.println("接收到消息:" + map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}


3:修改生产者传入类型

    /**
     * 保存商品查看记录
     * @param goodsId
     */
    private void saveWatchLog(String goodsId,String userId){
        Map<String,String> map = new HashMap<>();
        map.put("goodsId",goodsId);
        map.put("userId",userId);
        try {
             this.rabbitTemplate.convertAndSend("SaveWatchLog", JSONObject.toJSONString(map).getBytes());
        }catch (Exception e){
            log.error("保存商品查看记录MQ失败!E:{"+e.getMessage()+"}");
        }
    }



ok,完成。

上一篇 下一篇

猜你喜欢

热点阅读