Springboot整合RabbitMQ基本使用

来源:https://www.cnblogs.com/wandaren/archive/2022/11/19/16906262.html
-Advertisement-
Play Games

1、依賴 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> 2、rabbitmq鏈接配置 spring: r ...


1、依賴

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

2、rabbitmq鏈接配置

spring:
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: wq
    password: qifeng
    virtual-host: /
    #開啟ack
    listener:
      direct:
        acknowledge-mode: manual
        prefetch: 1 # 限制一次拉取消息的數量
      simple:
        acknowledge-mode: manual #採取手動應答
        #concurrency: 1 # 指定最小的消費者數量
        #max-concurrency: 1 #指定最大的消費者數量
        retry:
          enabled: true # 是否支持重試

3、生產者

  • 聲明交換機、隊列、綁定關於
package com.wanqi.mq;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/11/19
 * @Author wandaren
 */
@Configuration
public class RabbitMQConfig {
    public static final String EXCHANGE_NAME = "boot_topic_exchange";
    public static final String QUEUE_NAME = "boot_queue";
    //交換機
    @Bean("bootExchange")
    public Exchange bootExchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true)
                .build();
    }
    //
    @Bean("bootQueue")
    public Queue bootQueue(){
        return QueueBuilder.durable(QUEUE_NAME).build();
    }
    //隊列和交換機綁定關係
    /*
        知道哪個隊列
        知道哪個交換機
        知道routing key
     */
    @Bean
    public Binding bindingQueueExchange(@Qualifier("bootQueue") Queue queue,
                                        @Qualifier("bootExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
    }
}

  • 發送消息
package com.wanqi;

import com.wanqi.mq.RabbitMQConfig;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootMqProducersApplicationTests {
	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Test
	void contextLoads() {
		rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, "boot.test", "boot mq hello~~~");
	}

}

4、消費者

package com.wanqi.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/11/19
 * @Author wandaren
 */
@Component
public class RabbitMQListener {

    @RabbitListener(queues = {"boot_queue"})
    public void listenerQueue(Object msg, Message message, Channel channel) {
        final long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            System.out.println(msg.toString());
            System.out.println(new String(message.getBody()));
//            int x = 3/0;
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            try {
                channel.basicNack(deliveryTag, true, true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}

5、死信隊列

消息成為死信的三種情況
1、隊列消息長度到達限制;
2、消費者拒接消費消息,並且不重回隊列;
3、原隊列存在消息過期設置,消息到達超時時間未被消費;

5.1、聲明交換機、隊列、綁定隊列

  • topic模式
package com.wanqi.mq;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/11/19
 * @Author wandaren
 */
@Configuration
public class QDRabbitMQConfig {
    //交換機名稱
    public static final String ITEM_EXCHANGE = "item_exchange";
    public static final String DEAD_EXCHANGE = "dead_exchange";
    //隊列名稱
    public static final String ITEM_QUEUE = "item_queue";
    public static final String DEAD_QUEUE = "dead_queue";

    //聲明業務交換機
    @Bean("itemExchange")
    public Exchange itemExchange(){
        return ExchangeBuilder.topicExchange(ITEM_EXCHANGE).durable(true).build();
    }
    //聲明死信交換機
    @Bean("deadExchange")
    public Exchange deadExchange(){
        return ExchangeBuilder.topicExchange(DEAD_EXCHANGE).durable(true).build();
    }

    /**
     * 聲明普通隊列,設置隊列消息過期時間,隊列長度,綁定的死信隊列
     */
    @Bean("itemQueue")
    public Queue itemQueue(){
        return QueueBuilder
                .durable(ITEM_QUEUE)
                // 隊列消息過期時間
                .ttl(10000)
                // 隊列長度
                .maxLength(15)
                // 聲明當前隊列綁定的死信交換機
                .deadLetterExchange(DEAD_EXCHANGE)
                // 聲明當前隊列死信轉發的路由key
                .deadLetterRoutingKey("infoDead.haha")
                .build();
    }
    /**
     * 死信隊列,消費者需要監聽的隊列
     */
    @Bean("deadQueue")
    public Queue deadQueue(){
        return QueueBuilder
                .durable(DEAD_QUEUE)
                .build();
    }

    //綁定隊列和交換機(業務)
    @Bean
    public Binding itemQueueExchange(@Qualifier("itemQueue") Queue queue,
                                     @Qualifier("itemExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("infoRouting.#").noargs();
    }
    //綁定隊列和交換機(死信)
    @Bean
    public Binding deadQueueExchange(@Qualifier("deadQueue") Queue queue,
                                     @Qualifier("deadExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("infoDead.#").noargs();
    }

}

5.2、發送測試消息

package com.wanqi;

import com.wanqi.mq.RabbitMQConfig;
import com.wanqi.mq.RabbitMQConfig2;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootMqProducersApplicationTests {
	@Autowired
	private RabbitTemplate rabbitTemplate;
    
	// 原隊列存在消息過期設置,消息到達超時時間未被消費;
	@Test
	void contextLoads3() {
		MessageProperties messageProperties = new MessageProperties();
		// 設置過期時間,單位:毫秒
		messageProperties.setExpiration("5000");
		byte[] msgBytes = "rabbitmq ttl message ...".getBytes();
		Message message = new Message(msgBytes, messageProperties);

		//發送消息
		rabbitTemplate.convertAndSend(QDRabbitMQConfig.ITEM_EXCHANGE,"infoRouting.hehe",message);
		System.out.println("發送消息成功");
	}
    // 模擬隊列消息長度到達限制
	@Test
	void contextLoads4() {
		for (int i = 0; i < 20; i++) {
			rabbitTemplate.convertAndSend(QDRabbitMQConfig.ITEM_EXCHANGE,"infoRouting.hehe",i + "---message");

		}
	}
}

5.3、消費者

package com.wanqi.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/11/19
 * @Author wandaren
 */
@Component
public class RabbitMQListener {
    @RabbitListener(queues = {"dead_queue"})
    public void listenerQueue2(Object msg, Message message, Channel channel) {
        final long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            System.out.println(msg.toString());
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            try {
                channel.basicNack(deliveryTag, true, true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}

6、延遲隊列(TTL + 死信隊列)

6.1、聲明交換機、隊列、綁定隊列

  • direct模式

package com.wanqi.mq;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/11/19
 * @Author wandaren
 */
@Configuration
public class TtlQueueConfig {
    //普通交換機名稱
    public static final String X_CHANGE = "X_Exchange";
    //死信交換機名稱
    public static final String Y_DEAD_CHANGE = "Y_Exchange";
    //普通隊列
    public static final String QUEUE_A = "QA_QUEUE";
    public static final String QUEUE_B = "QB_QUEUE";
    //死信隊列
    public static final String DEAD_QUEUE_D = "QD_QUEUE";

    //聲明普通交換機
    @Bean("xExchange")
    public DirectExchange xExchange() {
        return ExchangeBuilder.directExchange(X_CHANGE).durable(true)
                .build();
    }

    //聲明死信交換機
    @Bean("yExchange")
    public DirectExchange yExchange() {
        return ExchangeBuilder.directExchange(Y_DEAD_CHANGE).durable(true)
                .build();
    }

    /**
     * 聲明隊列,延遲10秒
     */

    @Bean("queueA")
    public Queue queueA() {

        return QueueBuilder.durable(QUEUE_A)
                .deadLetterExchange(Y_DEAD_CHANGE) //死信交換機
                .deadLetterRoutingKey("YD")  //死信RoutingKey
                .ttl(10000)  //消息過期時間
                .build();
    }

    /**
     * 聲明隊列,延遲40秒
     *
     * @return
     */
    @Bean("queueB")
    public Queue queueB() {
        return QueueBuilder.durable(QUEUE_B)
                .deadLetterExchange(Y_DEAD_CHANGE) //死信交換機
                .deadLetterRoutingKey("YD")  //死信RoutingKey
                .ttl(40000)  //消息過期時間
                .build();
    }


    /**
     * 死信隊列,消費者需要監聽的隊列
     */
    @Bean("queueD")
    public Queue queueD() {
        return QueueBuilder.durable(DEAD_QUEUE_D).build();
    }


    //綁定  X_CHANGE綁定queueA
    @Bean
    public Binding queueABindingX(@Qualifier("queueA") Queue queueA, @Qualifier("xExchange") DirectExchange xExchange) {
        return BindingBuilder.bind(queueA).to(xExchange).with("XA");
    }

    //綁定  X_CHANGE綁定queueB
    @Bean
    public Binding queueBBindingX(@Qualifier("queueB") Queue queueB, @Qualifier("xExchange") DirectExchange xExchange) {
        return BindingBuilder.bind(queueB).to(xExchange).with("XB");
    }


    //綁定  Y_CHANGE綁定queueD
    @Bean
    public Binding queueDBindingY(@Qualifier("queueD") Queue queueD, @Qualifier("yExchange") DirectExchange yExchange) {
        return BindingBuilder.bind(queueD).to(yExchange).with("YD");
    }
}

6.2、發送消息

    @Test
    void contextLoads5() {
        String message = "延遲隊列消息";
        rabbitTemplate.convertAndSend(TtlQueueConfig.X_CHANGE, "XA", "TTL=10s的隊列:" + message);
        rabbitTemplate.convertAndSend(TtlQueueConfig.X_CHANGE, "XB", "TTL=40s的隊列:" + message);
    }

6.3、消費

package com.wanqi.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/11/19
 * @Author wandaren
 */
@Component
public class RabbitMQListener {
    @RabbitListener(queues = "QD_QUEUE")
    public void receiveMessage(Object msg,Message message, Channel channel){
        final long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            System.out.println(msg.toString());
            System.out.print("當前時間: " + new Date());
            System.out.println("  收到死信隊列的消息:" + msg);
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            try {
                channel.basicNack(deliveryTag, true, true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 案例分析: 如圖所示,頁面載入時有數據回填,同時實現select表單同步和圖片上傳,保存後上傳至伺服器等功能 HTML模板: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA ...
  • 先舉個例子:電商系統,用戶下單可以使用卡券支付。此時,訂單的金額會有兩部分構成:商品金額 和 卡券抵扣金額。通常,這樣的信息在訂單詳情頁也會展示出來。那麼,我們的訂單表裡,關於金額,應該有三個欄位:商品金額、卡券抵扣金額 和 訂單金額。 先舉個例子,在ToB的系統中,客戶通常會通過銷售代表來引入和維 ...
  • 從基礎的角度看,設計模式是研究類本身或者類與類之間的協作模式,是進行抽象歸納的一個很好的速成思路。後面閱讀設計模式後,為了加深理解,對相關圖片進行了描繪和微調。從技術的角度已經有很多好的總結,本文會換一種角度思考,既然設計模式研究的是類與類的關係,我們作為工作的個體,一些工作中的策略是不是也可以進行... ...
  • 5.8 導入其他介面代碼 第2-1-2章 傳統方式安裝FastDFS-附FastDFS常用命令 第2-1-3章 docker-compose安裝FastDFS,實現文件存儲服務 第2-1-5章 docker安裝MinIO實現文件存儲服務-springboot整合minio-minio全網最全的資料 ...
  • # 1.函數 # 函數就是將一段具有獨特功能的代碼段整合到一個整體並命名 # 在需要的位置調用這個名稱即可完成對應的需求 # 函數的作用:封裝代碼(方便管理),實現代碼重用 print('1.函數作用') name_list = ['小明', '小剛'] # 列表 print(len(name_li ...
  • 不知道大家的電腦桌面一般用的什麼類型的壁紙? 早上來上班,打開電腦,被漂亮的桌面壁紙所吸引,年底將近,這又是哪個地方的節日? 才曉得,原來這是泰國第二大城市清邁的“天燈節”,把🏮送上天空是對神靈的尊敬,代表著擺脫厄運,祈求好運 燈籠通常是由宣紙製成,把點燃的蠟燭固定在中心。火能產生足夠的熱量使燈籠 ...
  • 使用類模板實現STL Vector,點擊查看代碼 #include <iostream> using namespace std; template<typename T> class MyVector { public: //構造函數 MyVector<T>(int size = 10) { T ...
  • 1、Erlnag安裝 1.1、 安裝Erlang版本要求 Erlang安裝需要對應各自的版本 http://www.rabbitmq.com/which-erlang.html 1.2、 Erlang安裝 1、目錄準備 cd /usr/local/src/ mkdir rabbitmq cd rab ...
一周排行
    -Advertisement-
    Play Games
  • C#TMS系統代碼-基礎頁面BaseCity學習 本人純新手,剛進公司跟領導報道,我說我是java全棧,他問我會不會C#,我說大學學過,他說這個TMS系統就給你來管了。外包已經把代碼給我了,這幾天先把增刪改查的代碼背一下,說不定後面就要趕鴨子上架了 Service頁面 //using => impo ...
  • 委托與事件 委托 委托的定義 委托是C#中的一種類型,用於存儲對方法的引用。它允許將方法作為參數傳遞給其他方法,實現回調、事件處理和動態調用等功能。通俗來講,就是委托包含方法的記憶體地址,方法匹配與委托相同的簽名,因此通過使用正確的參數類型來調用方法。 委托的特性 引用方法:委托允許存儲對方法的引用, ...
  • 前言 這幾天閑來沒事看看ABP vNext的文檔和源碼,關於關於依賴註入(屬性註入)這塊兒產生了興趣。 我們都知道。Volo.ABP 依賴註入容器使用了第三方組件Autofac實現的。有三種註入方式,構造函數註入和方法註入和屬性註入。 ABP的屬性註入原則參考如下: 這時候我就開始疑惑了,因為我知道 ...
  • C#TMS系統代碼-業務頁面ShippingNotice學習 學一個業務頁面,ok,領導開完會就被裁掉了,很突然啊,他收拾東西的時候我還以為他要旅游提前請假了,還在尋思為什麼回家連自己買的幾箱飲料都要叫跑腿帶走,怕被偷嗎?還好我在他開會之前拿了兩瓶芬達 感覺感覺前面的BaseCity差不太多,這邊的 ...
  • 概述:在C#中,通過`Expression`類、`AndAlso`和`OrElse`方法可組合兩個`Expression<Func<T, bool>>`,實現多條件動態查詢。通過創建表達式樹,可輕鬆構建複雜的查詢條件。 在C#中,可以使用AndAlso和OrElse方法組合兩個Expression< ...
  • 閑來無聊在我的Biwen.QuickApi中實現一下極簡的事件匯流排,其實代碼還是蠻簡單的,對於初學者可能有些幫助 就貼出來,有什麼不足的地方也歡迎板磚交流~ 首先定義一個事件約定的空介面 public interface IEvent{} 然後定義事件訂閱者介面 public interface I ...
  • 1. 案例 成某三甲醫預約系統, 該項目在2024年初進行上線測試,在正常運行了兩天後,業務系統報錯:The connection pool has been exhausted, either raise MaxPoolSize (currently 800) or Timeout (curren ...
  • 背景 我們有些工具在 Web 版中已經有了很好的實踐,而在 WPF 中重新開發也是一種費時費力的操作,那麼直接集成則是最省事省力的方法了。 思路解釋 為什麼要使用 WPF?莫問為什麼,老 C# 開發的堅持,另外因為 Windows 上已經裝了 Webview2/edge 整體打包比 electron ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...