1.pom,xml引入下面的架,版本自己选
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId> <version>2.1.3.RELEASE</version>
</dependency>
2.application.yml,配置连接rabbmitmq连接信息
spring:
rabbitmq:
host: localhost
port: 5672
username: admin
password: admin
3.创建队列
@Configuration
public class RabbitMqConfig {
@Bean
public Queue helloWorldQueue() {
return new Queue("helloWorld_queue_test1",true);
}
}
4.发布消息
@Component
public class Sender {
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* 发送消息
*/
public void send() {
String message = "message" + new Date();
rabbitTemplate.convertAndSend("helloWorld_exchange_test1","hello_world_route_key",message);
}
}
5.订阅消息
@RabbitListener(queues = "helloWorld_queue_test1")
@Component
public class Receiver {
/**
* 消费
* @param message
*/
@RabbitHandler
public void helloWorld(String message) {
System.out.println("Receiver1:" + message);
}
}
注意:消息发布了,这个方法会被异步调用
6.测试
pom.xml需要引入如下包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.1.3.RELEASE</version> <scope>test</scope>
</dependency>
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RabbitMqServerApplication.class)
public class SendTest {
@Autowired
private Sender sender;
@Test
public void testSend() {
sender.send();
}
}
发送的消息成功被消费
控制台输出
Receiver1:messageWed Jun 05 15:18:04 CST 2019
2019-06-05 15:18:04.846 INFO 10124 --- [ Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2019-06-05 15:18:04.849 INFO 10124 --- [ Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Waiting for workers to finish.
2019-06-05 15:18:05.581 INFO 10124 --- [ Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2019-06-05 15:18:05.584 INFO 10124 --- [ Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Shutdown ignored - container is not active already
2019-06-05 15:18:05.584 INFO 10124 --- [ Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Shutdown ignored - container is not active already
2019-06-05 15:18:05.584 INFO 10124 --- [ Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'