1. springBoot項目下引入amqp starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
amqp-starter 會引入如下jar包
[INFO] \- org.springframework.boot:spring-boot-starter-amqp:jar:2.1.5.RELEASE:compile
[INFO] +- org.springframework:spring-messaging:jar:5.1.7.RELEASE:compile
[INFO] \- org.springframework.amqp:spring-rabbit:jar:2.1.6.RELEASE:compile
[INFO] +- org.springframework.amqp:spring-amqp:jar:2.1.6.RELEASE:compile
[INFO] | \- org.springframework.retry:spring-retry:jar:1.2.4.RELEASE:compile
[INFO] +- com.rabbitmq:amqp-client:jar:5.4.3:compile
[INFO] | \- org.slf4j:slf4j-api:jar:1.7.26:compile
[INFO] \- org.springframework:spring-tx:jar:5.1.7.RELEASE:compile
2. springBoot 配置文件下配置rabbitMQ屬性
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
3. 創(chuàng)建Queue并注入到spring容器中
@Configuration
public class QueueConfig {
@Bean
public Queue queue() {
return new Queue("test_queue");
}
}
4. Sender 發(fā)送數(shù)據(jù)到Queue
@Component
public class Sender {
@Autowired
private AmqpTemplate template;
public void send(String message) {
template.convertAndSend("test_queue",message);
}
}
其中AmqpTemplate是SpringBoot生成的默認(rèn)實(shí)現(xiàn),在代碼里面可以直接引入使用。
5. Receiver 消費(fèi)Queue中的數(shù)據(jù)
@Component
@RabbitListener(queues = "test_queue")
public class Receiver {
Logger logger = LoggerFactory.getLogger(Receiver.class.getName());
@RabbitHandler
public void process(String message) {
logger.info(message);
}
}
添加Queue的listener,并對收到的消息進(jìn)行處理。注意,receiver要注入到容器中(@Component)才能對消息進(jìn)行監(jiān)聽。
上面采用Direct的方式來使用queue。接下來使用Topic、Fanout...