springboot整合activemq

一、activemq簡介

Apache ActiveMQ是Apache Software Foundation(ASF)的一個開源消息代理項目,它是使用Java語言編寫的消息中間件,基於JMS(Java Message Service)規範,提供了常見的消息傳遞模型(點對點模型和發布/訂閱模型)來支持應用程序之間的通信。

二、springboot整合activemq基礎

在使用springboot整合activemq之前,需要引入以下依賴。

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

在application.properties或application.yml文件中配置activemq的基本屬性。

spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.in-memory=true

其中,broker-url是activemq連接的地址,user和password是登錄activemq的用戶名和密碼,in-memory表示是否使用內存存儲消息,默認為false表示使用持久化存儲。

在代碼中注入JmsTemplate來發送和接收消息。以下是一個簡單的例子。

@Service
public class Producer {
 
    @Autowired
    JmsTemplate jmsTemplate;
    
    public void sendMessage(String queueName, String message) {
        jmsTemplate.send(queueName, session -> session.createTextMessage(message));
    }
}

Producer中使用JmsTemplate發送消息,其中queueName為消息隊列的名稱,message為發送的消息內容。接收消息的代碼如下。

@Service
public class Consumer {
 
    @JmsListener(destination = "myqueue")
    public void receiveMessage(String message) {
        System.out.println("Received message: " + message);
    }
}

Consumer中使用@JmsListener註解來監聽消息隊列,destination表示監聽的隊列名稱,receiveMessage方法接收消息內容。

三、activemq高級用法

1. 事務支持

在消息處理過程中,需要保證消息的可靠性。使用activemq的事務支持可以滿足此需求。

@Service
public class Producer {
 
    @Autowired
    JmsTemplate jmsTemplate;
    
    public void sendMessage(String queueName, String message) {
        jmsTemplate.execute(session -> {
            Message msg = session.createTextMessage(message);
            session.createProducer(session.createQueue(queueName)).send(msg);
            return null;
        });
    }
}

在發送消息的方法中,使用jmsTemplate.execute來開啟一個事務,在事務中發送消息,並通過return null提交事務。如果提交成功,消息會被成功發送;否則,消息將被回滾。

2. 發布/訂閱模型

在使用發布/訂閱模型時,需要定義主題(topic)。

@Configuration
public class TopicConfig {
 
    @Bean
    public Topic topic() {
        return new ActiveMQTopic("mytopic");
    }
}

定義主題的代碼如上所示。在Producer中發送消息時,使用convertAndSend方法,而不是send方法。

@Service
public class Producer {
 
    @Autowired
    JmsTemplate jmsTemplate;
    
    public void sendMessage(String topicName, String message) {
        jmsTemplate.convertAndSend(topicName, message);
    }
}

在Consumer中接收消息時,使用@JmsListener註解,並設置containerFactory為JmsListenerContainerFactory。

@Service
public class Consumer {
 
    @Autowired
    JmsListenerContainerFactory jmsListenerContainerFactory;
 
    @JmsListener(destination = "mytopic", containerFactory = "jmsListenerContainerFactory")
    public void receiveMessage(String message) {
        System.out.println("Received message: " + message);
    }
}

3. 消息過濾

activemq支持根據一定的條件過濾消息,從而只選擇特定的消息進行消費。在定義JmsListener時,可以設置selector參數,該參數定義了選擇哪些消息進行消費。

@Service
public class Consumer {
 
    @JmsListener(destination = "myqueue", selector = "color = 'blue'")
    public void receiveBlueMessage(String message) {
        System.out.println("Received message: " + message);
    }
 
    @JmsListener(destination = "myqueue", selector = "color = 'red'")
    public void receiveRedMessage(String message) {
        System.out.println("Received message: " + message);
    }
}

以上代碼中,JmsListener的selector參數分別設置為color=’blue’和color=’red’,表示只選擇color屬性為blue或red的消息進行消費。

4. 死信隊列

activemq支持死信隊列(Dead Letter Queue,DLQ),當消息處理失敗時,可以將該消息發送到DLQ中。在使用DLQ時,需要定義主題和隊列。

@Configuration
public class TopicConfig {
 
    @Bean
    public Topic topic() {
        return new ActiveMQTopic("mytopic.dlq");
    }
}
 
@Configuration
public class QueueConfig {
 
    @Bean
    public Queue queue() {
        return new ActiveMQQueue("myqueue");
    }
 
    @Bean
    public RedeliveryPolicy redeliveryPolicy() {
        RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
        redeliveryPolicy.setMaximumRedeliveries(3);
        redeliveryPolicy.setInitialRedeliveryDelay(3000);
        redeliveryPolicy.setRedeliveryDelay(3000);
        redeliveryPolicy.setUseExponentialBackOff(false);
        return redeliveryPolicy;
    }
 
    @Bean
    public RedeliveryPolicyMap redeliveryPolicyMap() {
        RedeliveryPolicyMap redeliveryPolicyMap = new RedeliveryPolicyMap();
        redeliveryPolicyMap.setDefaultEntry(redeliveryPolicy());
        return redeliveryPolicyMap;
    }
 
    @Bean
    public JmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setConcurrency("3-10"); // 控制消費者個數
        factory.setSessionTransacted(true);
        factory.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);
 
        // 配置死信隊列
        RedeliveryPlugin redeliveryPlugin = new RedeliveryPlugin();
        redeliveryPlugin.setRedeliveryPolicyMap(redeliveryPolicyMap());
        RedeliveryPlugin[] plugins = { redeliveryPlugin };
        factory.setPlugins(plugins);
        return factory;
    }
}

以上代碼中,定義了主題為mytopic.dlq的死信隊列,在QueueConfig中配置了隊列,並定義了RedeliveryPolicy和RedeliveryPolicyMap,用於配置消息重發的策略。在JmsListenerContainerFactory中設置了sessionTransacted為true,sessionAcknowledgeMode為CLIENT_ACKNOWLEDGE,表示使用事務和客戶端確認模式,並通過RedeliveryPlugin來將未處理的消息發送到DLQ中。

四、總結

本文介紹了springboot整合activemq的基礎和高級用法,包括事務支持、發布/訂閱模型、消息過濾和死信隊列。通過本文的學習,讀者可以更加深入地了解activemq的應用場景和使用方法。

原創文章,作者:ERWAK,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/332906.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
ERWAK的頭像ERWAK
上一篇 2025-01-27 13:34
下一篇 2025-01-27 13:34

相關推薦

  • 從ga角度解讀springboot

    springboot作為目前廣受歡迎的Java開發框架,其中的ga機制在整個開發過程中起著至關重要的作用。 一、ga是什麼 ga即Group Artifacts的縮寫,它是Mave…

    編程 2025-04-29
  • SpringBoot Get方式請求傳參用法介紹

    本文將從以下多個方面對SpringBoot Get方式請求傳參做詳細的闡述,包括URL傳參、路徑傳參、請求頭傳參、請求體傳參等,幫助讀者更加深入地了解Get請求方式下傳參的相關知識…

    編程 2025-04-27
  • SpringBoot如何設置不輸出Info日誌

    本篇文章將帶您了解如何在SpringBoot項目中關閉Info級別日誌輸出。 一、為什麼要關閉Info日誌 在開發中,我們經常會使用Log4j、Logback等框架來輸出日誌信息,…

    編程 2025-04-27
  • 解決springboot中scanBasePackages無法讀取子包的問題

    在使用springboot搭建項目時,可能會遇到scanBasePackages無法讀取子包的問題。本文將從幾個方面詳細闡述如何解決這個問題。 一、問題描述 在使用Springbo…

    編程 2025-04-25
  • SpringBoot請求參數綁定

    解答:SpringBoot請求參數綁定是指將HTTP請求中的參數與Controller方法的參數綁定起來,使得參數的傳遞變得簡單和方便。下面我們將從多個方面對SpringBoot請…

    編程 2025-04-25
  • SpringBoot文件上傳詳解

    一、前言 隨著互聯網的發展,文件上傳成為了必備的功能之一,而SpringBoot作為目前最流行的開發框架之一,為文件上傳提供了便捷而強大的解決方案。 二、使用multipart/f…

    編程 2025-04-24
  • 使用SpringBoot開發高效的Web服務應用

    一、快速入門 SpringBoot可以讓你更快速地搭建Web應用,它為開發者提供了許多使用時省去了很多配置代碼的便利。在這裡,我們將通過一個簡單的示例來介紹如何使用SpringBo…

    編程 2025-04-24
  • 使用SpringBoot連接MySQL資料庫

    SpringBoot是一個用於構建基於Spring框架的應用程序的快速開發工具,它提供了許多函數和庫,使開發人員能夠快速構建應用程序並將其部署到雲中。同時,MySQL是一個流行的關…

    編程 2025-04-24
  • Nacos SpringBoot版本詳解

    一、Nacos簡介 Nacos是一個開源的分散式配置管理和服務發現平台,為微服務架構提供了基礎設施支持。它可以幫助開發人員解決微服務架構中的服務發現、服務配置、服務元數據管理和流量…

    編程 2025-04-23
  • SpringBoot的好處

    一、簡化開發流程 用SpringBoot開發項目可以大大減少繁瑣的配置工作,大部分的配置都是默認配置,只需要添加相應的依賴,即可完成開發工作。SpringBoot可以讓你更專註於業…

    編程 2025-04-23

發表回復

登錄後才能評論