Spring Boot (5) 整合 RabbitMQ

一、前言

RabbitMQ是實現了AMQP(高級消息隊列協議)的開源消息中間件,RabbitMQ服務器是用Erlang(面向併發的編程語言)編寫的。

RabbitMQ官網下載地址:https://www.rabbitmq.com/download.html

Docker部署則執行如下命令即可

<code># RABBITMQ_DEFAULT_USER:用戶名,RABBITMQ_DEFAULT_PASS:密碼 這裡修改為自己的即可docker run -d --name rabbitmq -p 5672:5672 -p 15672:15672 -v `pwd`/rabbitmq/data:/var/lib/rabbitmq --hostname my-rabbit --restart=always -e RABBITMQ_DEFAULT_VHOST=my_vhost -e RABBITMQ_DEFAULT_USER=admin -e RABBITMQ_DEFAULT_PASS=admin rabbitmq:3-management/<code>
Spring Boot (5) 整合 RabbitMQ

溫馨小提示:本文只是簡單的通過rabbitmq去發送消息和接收消息,適用於新手簡單入門瞭解~

二、SpringBoot 整合 RabbitMQ


1、pom.xml 中引入 rabbitmq 依賴


<code><dependency>   <groupid>org.springframework.boot/<groupid>   <artifactid>spring-boot-starter-amqp/<artifactid>/<dependency>/<code>


2、application.yml 中配置 rabbitmq


<code>spring:  # RabbitMQ配置  rabbitmq:    host: 127.0.0.1    port: 5672    # 填寫自己安裝rabbitmq時設置的賬號密碼,默認賬號密碼為`guest`    username: admin    password: admin    virtual-host: my_vhost # 填寫自己的虛擬機名,對應可查看 `127.0.0.1:15672/#/users` 下Admin中的`Can access virtual hosts`信息/<code>


3、rabbitmq配置文件 - 配置一個簡單的Queue(消息隊列)


生產者發送消息到隊列,消費者從隊列中獲取消息

<code>@Configurationpublic class RabbitConfig {    public static final String QUEUE_KEY = "hello_world";    @Bean    public Queue queue() {        // durable: true 標識開啟消息隊列持久化 (隊列當中的消息在重啟rabbitmq服務的時候還會存在)        return new Queue(QUEUE_KEY, true);    }}/<code> 


4、生產者 - 發送消息


<code>@Slf4j@Componentpublic class MsgSender {    @Autowired    private AmqpTemplate rabbitTemplate;    public void send() {        String msgContent = "Hello World ~";        log.info("生產者發送消息 : " + msgContent);        this.rabbitTemplate.convertAndSend(RabbitConfig.QUEUE_KEY, msgContent);    }}/<code>


5、消費者 - 接收消息


<code>@Slf4j@Component@RabbitListener(queues = RabbitConfig.QUEUE_KEY)public class MsgReceiver {    @RabbitHandler    public void process(String msg) {        log.info("消費者接收消息 : " + msg);    }}/<code>


6、測試


<code>@RestControllerpublic class RabbitController {    @Autowired    private MsgSender msgSender;    @GetMapping(value = "/sendMsg", produces = "application/json;charset=utf-8")    @ApiOperation(value = "發送消息", httpMethod = "GET", response = ApiResult.class)    public ApiResult sendMsg() {        msgSender.send();        return ApiResult.ok();    }}/<code>


7、運行項目,訪問 http://127.0.0.1:8080/sendMsg

Spring Boot (5) 整合 RabbitMQ

本文案例demo源碼

https://gitee.com/zhengqingya/java-workspace


分享到:


相關文章: