一、項目配置
1)引入maven坐標
<!--amqp--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> <version>2.0.3.RELEASE</version> </dependency>
2)application.yml加入RabbitMQ的連接配置
spring.rabbitmq.host: localhost spring.rabbitmq.port: 5672 spring.rabbitmq.username: guest spring.rabbitmq.password: guest
二、消息的發送和接收
1)創建指定名稱的消息隊列
@Configuration public class RabbitConfig { @Bean public Queue helloQueue() { return new Queue("hello"); } }
2)創建消息接收者
@Component @RabbitListener(queues = "hello") public class Receiver { @RabbitHandler public void process(String hello) { System.out.println("Receiver : " + hello); } }
3)創建消息發送着
@Component public class Sender { @Autowired private AmqpTemplate rabbitTemplate; public void send() { String context = "hello " + new Date(); System.out.println("Sender : " + context); this.rabbitTemplate.convertAndSend("hello", context); } }
4)創建發送消息的測試類
@RunWith(SpringRunner.class) @WebAppConfiguration @SpringBootTest public class RabbitMQSenderTest { @Autowired private Sender sender; @Test public void hello() throws Exception { sender.send(); } }