Spring Boot(十九):异步消息AMQP(RabbitMQ)

介绍

pom文件引入:

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

注解启用:@EnableRabbit

AmqpConfiguration:

1
2
3
4
5
6
7
8
9
import org.springframework.amqp.core.Queue;

@Configuration
public class AmqpConfiguration {
@Bean
public Queue queue() {
return new Queue("dodd.queue");
}
}

AmqpComponent:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Component
public class AmqpComponent {
@Autowired
private AmqpTemplate amqpTemplate;

public void send(String msg) {
this.amqpTemplate.convertAndSend("dodd.queue", msg);
}

@RabbitListener(queues = "dodd.queue")
public void receiveQueue(String text) {
System.out.println("接受到:" + text);
}
}

测试类:

1
2
3
4
5
6
7
@Autowired
private AmqpComponent amqpComponent;

@Test
public void send() {
amqpComponent.send("hello world");
}