Springboot接入RabbitMQ详细教程
Posted renyutao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot接入RabbitMQ详细教程相关的知识,希望对你有一定的参考价值。
本文适用于对 RabbitMQ 有所了解的人,在此不讨论MQ的原理,只讨论如何接入。其实Spring Boot 集成 RabbitMQ 非常简单,本文章使用的是Spring Boot 提供了spring-boot-starter-amqp
项目对消息各种支持。
接下来将进入正题,六步轻松教你接入RabbitMQ
1.配置pom文件所依赖的主要jar包
<dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit</artifactId> <version>2.0.4.RELEASE</version> </dependency>
2.配置文件(application.properties)
## rabbitmq spring.rabbitmq.host=127.0.0.1 spring.rabbitmq.port=5672 spring.rabbitmq.username=root spring.rabbitmq.password=root spring.rabbitmq.virtual-host=/ # rabbitmq消息确认 spring.rabbitmq.publisher-confirms=true spring.rabbitmq.publisher-returns=true ## rabbitmq-config rabbitmq.exchange-key = rabbitmq.test.exchange rabbitmq.routing-key = rabbitmq.test.routing.key rabbitmq.queue-name=rabbitmq.queue.name.test
3.交换机和队列绑定配置
@Value("$rabbitmq.queue-name") String queueName; @Value("$rabbitmq.exchange-key") String exchangeKey; @Value("$rabbitmq.routing-key") String routingKey; @Bean(value = "$rabbitmq.queue-name") public Queue initOrderCancelQueue() return new Queue(queueName) ; @Bean(value = "$rabbitmq.exchange-key") public CustomExchange customExchange() Map<String,Object> args=new HashMap<>(); return new CustomExchange(exchangeKey,"topic",true,false,args); @Bean public Binding binding(@Qualifier(value = "$rabbitmq.queue-name") Queue queue, @Qualifier(value = "$rabbitmq.exchange-key") CustomExchange exchange) return BindingBuilder .bind(queue) .to(exchange) .with(routingKey) .and(exchange.getArguments());
4.生产者
@Value("$rabbitmq.exchange-key") String exchangeKey; @Autowired private AmqpTemplate amqpTemplate; /** * 发送MQ * @param routingKey * @param obj 参数 */ public void sendNotification(String routingKey, Object obj) this.amqpTemplate.convertAndSend(exchangeKey,routingKey,obj);
5消费者
@RabbitHandler @RabbitListener(queues = "$rabbitmq.queue-name") public void receiveRabbitmqMsg(Message msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) String funcName="接收到RabbitmqMsg"; logger.info(":",funcName,msg); try catch(Exception e) finally
6.测试
@Autowired RabbitmqProducer producer; @Value("$rabbitmq.routing-key") String routingKey; public void sendMsg() TestModel testModel =new TestModel(); testModel.setName("fxx"); testModel.setAge(18); testModel.setGender("girl"); try producer.sendNotification(routingKey,testModel); catch (Exception e) logger.error("系统异常:"+e.toString());
搞定!就这么简单,赶快自己动手试试吧
以上是关于Springboot接入RabbitMQ详细教程的主要内容,如果未能解决你的问题,请参考以下文章
mybatisgenerator集成springBoot,并常见使用教程(详)