SpringBoot下使用RabbitMQ发送消息,最简单或者默认的方式是发送和接受string类型的,如果你遇到要发送复杂的Java实体类,那么简单的办法就是将其序列化成JSON后发送(例如使用Jackson的ObjectMapper工具),接收方再将JSON消息反序列化成Java实体类,但是这样做显然不够优雅,要处理的重复代码很多。我们可以做配置,让程序自动完成转化这样事情。
新增相关依赖
pom.xml 下增加mq相关依赖以及fastjson的依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> </dependency>
发送方使用
新增RabbitMQ相关设置,给MQ设定MessageConverter为Jackson2JsonMessageConverter,来达到自动将Java的Object转成JSON。
@Configuration public class RabbitmqConfig { @Bean public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) { RabbitTemplate rabbitTemplate = new RabbitTemplate(); rabbitTemplate.setConnectionFactory(connectionFactory); rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter()); return rabbitTemplate; } }
@Autowired RabbitTemplate rabbitTemplate; # 用mq发送java的Object,具体使用看mq的API rabbitTemplate.convertAndSend("some_queue_name", someMessageObject);
接收方使用
@Component public class ReceiveConfig { @Autowired private RabbitTemplate rabbitTemplate; @Bean public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory){ SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); factory.setMessageConverter(new Jackson2JsonMessageConverter()); //每次处理数据数量,提高并发量 factory.setPrefetchCount(250); return factory; } @RabbitListener(queues = "some_queue_name", concurrency = "1-3") @RabbitHandler public void handleCodeQueue(@Payload SomeMessageObject someMessageObject, Channel channel, Message message) throws IOException { long deliveryTag = message.getMessageProperties().getDeliveryTag(); logger.info("消费的消息来⾃的队列名为:" + message.getMessageProperties().getConsumerQueue()); // 其他代码省略 } }
文章评论