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. 创建Queue并注入到spring容器中
@Configuration
public class QueueConfig {
@Bean
public Queue queue() {
return new Queue("test_queue");
}
}
4. Sender 发送数据到Queue
@Component
public class Sender {
@Autowired
private AmqpTemplate template;
public void send(String message) {
template.convertAndSend("test_queue",message);
}
}
其中AmqpTemplate是SpringBoot生成的默认实现,在代码里面可以直接引入使用。
5. Receiver 消费Queue中的数据
@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,并对收到的消息进行处理。注意,receiver要注入到容器中(@Component)才能对消息进行监听。
上面采用Direct的方式来使用queue。接下来使用Topic、Fanout...
转载于:https://www.jianshu.com/p/9cf3e883b4c0