RabbitMq 实现消息自动序列化和反序列化的配置

配置 

@Configuration
public class RabbitMqConfig implements RabbitListenerConfigurer {



    //以下配置RabbitMQ消息服务
    @Autowired
    public ConnectionFactory connectionFactory;

    @Bean
    public DefaultMessageHandlerMethodFactory myHandlerMethodFactory() {
        DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
        // 这里的转换器设置实现了 通过 @Payload 注解 自动反序列化message body
        factory.setMessageConverter(new MappingJackson2MessageConverter());
        return factory;
    }

    @Override
    public void configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) {
        registrar.setMessageHandlerMethodFactory(myHandlerMethodFactory());
    }

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setConcurrentConsumers(3);
        factory.setMaxConcurrentConsumers(10);
        return factory;
    }
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }


    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        // 这里的转换器设置实现了发送消息时自动序列化消息对象为message body
        template.setMessageConverter(jsonMessageConverter());
        return template;
    }
}

 

发送消息

@RestController
public class SendMessageController {



    @GetMapping("/sendDtoMessage")
    public String sendDtoMessage() {

        HelloDTO helloDTO = new HelloDTO();
        rabbitTemplate.convertAndSend("TestFanoutExchange", "TestFanoutKey", helloDTO);
        return "ok";
    }



}

 

 

接收消息

@Service
public class FanoutMessageReceiveServiceImpl {


   
 @RabbitListener(
            bindings = {@QueueBinding(value = @Queue("TestFanoutQueue"), exchange = @Exchange(value = "TestFanoutExchange", type = ExchangeTypes.FANOUT))}
    )
    public void messageHandler(@Payload HelloDTO helloDTO) {

        System.out.println("helloDTO = " + helloDTO);

    }

}

 

你可能感兴趣的:(后端,#,JAVA)