1:添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2:參數配置
spring.rabbitmq.host = 192.168.0.1
spring.rabbitmq.port = 5672
spring.rabbitmq.username = admin
spring.rabbitmq.password = 123456
spring.rabbitmq.virtual-host = /
spring.rabbitmq.connection-timeout = 5000
spring.rabbitmq.listener.simple.concurrency = 5
spring.rabbitmq.listener.simple.max-concurrency = 10
spring.rabbitmq.listener.simple.acknowledge-mode = manual
spring.rabbitmq.listener.simple.prefetch = 1
3:設置消息消費的監聽器
@Component
public class OrderConsumer {
@RabbitListener(bindings = @QueueBinding(
value=@Queue(value="order-queue",durable = "true"),
exchange = @Exchange(name = "order-exchange", durable = "true" ,type = "topic"),
key = "order.#"
)
)
@RabbitHandler
public void receiveOrder(@Payload JSONObject vo,@Headers Map<String,Object> headers , Channel channel) throws Exception{
System.out.println("--------消費者已經獲取到消息-------");
System.out.println("order>>"+vo.toString());
long id = Long.valueOf(headers.get(AmqpHeaders.DELIVERY_TAG).toString());
channel.basicAck(id , false);
}
}
注意@RabbitListener的使用方式,其中binding操作以及exchange和queue的關係生成
4:啓動項目
如果在rabbitMQ中有消息生成,那麼在同一個路由exchange和同一個規則下的queue隊列中,即可獲取消息對象。