一、引入外部依赖 https://mvnrepository.com/
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> <version>2.4.4</version> </dependency>
二、代码
spring.application.name=demo spring.rabbitmq.addresses=192.168.1.xxx:8088 spring.rabbitmq.username=admin spring.rabbitmq.password=admin
spring.rabbitmq.host: localhost spring.rabbitmq.port: 5672 spring.rabbitmq.username: guest spring.rabbitmq.password: guest
package com.example.mq; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MySend { @Autowired private AmqpTemplate amqpTemplate; public void send(){ amqpTemplate.convertAndSend("testQue","testMsg"); } }
package com.example.mq; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class MyReceiver { @RabbitHandler @RabbitListener(queues = "testQue") public void receive(String text){ System.out.println(text+"....."); } }
package com.example.controller; import com.example.mq.MySend; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class MQController { @Autowired private MySend mySend; @Autowired private JmsTemplate jmsTemplate; @RequestMapping("/activeMQ") @ResponseBody public String tests(){ jmsTemplate.convertAndSend("testname","testMsg"); return "ok"; } @RequestMapping("/rabbitMQ") @ResponseBody public String test2(){ mySend.send(); return "ok"; } }