美文网首页
7 RabbitMQ异常:No method found for

7 RabbitMQ异常:No method found for

作者: 滔滔逐浪 | 来源:发表于2023-10-26 09:36 被阅读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,完成。

相关文章

网友评论

      本文标题:7 RabbitMQ异常:No method found for

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