1. 程式人生 > 其它 >Spring Boot 入門(九)使用RabbitMQ

Spring Boot 入門(九)使用RabbitMQ

maven

<!--rabbitmq-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

配置檔案

spring.rabbitmq.host=192.168.233.128
spring.rabbitmq.port=5672
spring.rabbitmq.username=root
spring.rabbitmq.password
=123456

建立生產者

@Autowired
RabbitTemplate rabbitTemplate;

/**
* sendRabbitMQ
* 預設Exchange: (AMQP default)
* direct模式:通過routingKey關聯
*/
@RequestMapping("/sendRabbitMQ")
public String sendRabbitMQ(String msg) {
    rabbitTemplate.convertAndSend("queue.A", msg);
    return "傳送成功";
}

建立消費者

package com.example.demo.rabbitmq;

import com.rabbitmq.client.Channel; import org.springframework.amqp.rabbit.annotation.Queue; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.support.AmqpHeaders; import org.springframework.messaging.handler.annotation.Header; import org.springframework.stereotype.Component; @Component
public class QueueListener { @RabbitListener(queuesToDeclare = @Queue("queue.A")) public void receiveMsgA(String msg, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) { System.out.println("收到訊息A:" + msg); } }
queuesToDeclare(如果佇列不存在則建立)

傳送訊息