记一次springboot整合rabbitMQ的list序列化问题

问题:平时传一个类的时候都会继承Serializable实现正确传输,这次我把list<Object>直接丢成了message,导致rabbitMQ不能序列化对象。报错

org.springframework.amqp.rabbit.support.ListenerExecutionFailedException: Failed to convert message

下面的整合步骤提供了解决方案:

在发送时,将list对象序列化能json字符串再发生

在接收时,反序列化中,由于java的类型擦除,我使用了TypeReference指定list的类型。当然这里需要保证其中的object是可序列化/反序列化的

 

springboot整合rabbitMQ的步骤:

1.引入pom

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

2.添加yaml配置

spring:
  rabbitmq:
    host: 192.168.88.95
    username: sunshine
    password: sunshine

3.创建生产者消费者类

生产者

@Component
public class Producer {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(String exchange, String routingKey, List<HistoryQuestionByAi> message){
        ObjectMapper objectMapper=new ObjectMapper();
        try{
            String jsonToString=objectMapper.writeValueAsString(message);
            rabbitTemplate.convertAndSend(exchange,routingKey,jsonToString);
        }catch (Exception e){
            throw new RuntimeException("消息发送失败");
        }

    }

}

消费者

@Component
@Slf4j
public class Consumer {
    @Autowired
    ESService esService;
    @RabbitListener(queues = "writeInEsQueue")
    public void handlerMessage(String message){
        log.info("接收到消息:{}",message);
        ObjectMapper objectMapper=new ObjectMapper();
        try {
            List<HistoryQuestionByAi>list=objectMapper.readValue(message, new TypeReference<List<HistoryQuestionByAi>>() {});

            esService.addES(list);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

配置类

@Configuration
public class RabbitMQConfig {
    @Bean
    public Queue writeInEsQueue(){
        return new Queue("writeInEsQueue");
    }

    @Bean
    public Exchange writeInEsExchange(){
        return new DirectExchange("writeInEsExchange");
    }

    @Bean
    public Binding binding(Queue writeInEsQueue,DirectExchange writeInEsExchange){
        return BindingBuilder.bind(writeInEsQueue).to(writeInEsExchange).with("writeInEsKey");
    }
}

 

posted @ 2024-07-09 23:50  天启A  阅读(228)  评论(0)    收藏  举报