共用方式為


在 Spring 中使用 Azure Event Grid

本文將教你如何使用 Azure Event Grid 將事件傳送到主題,並使用 Service Bus 佇列作為 Event Handler,在 Spring Boot 應用程式中接收。

Azure Event Grid 服務是一個高度可擴展、完全管理的 Pub Sub 訊息分發服務,利用 MQTT 和 HTTP 協定提供彈性的訊息消費模式。

先決條件

訂閱自定義主題

請依照以下步驟建立事件訂閱,告訴事件網格將事件傳送至 Service Bus 佇列:

  1. 在 Azure 入口網站中,導覽到你的事件網格主題實例。
  2. 選取工具列上的 [事件訂閱 ]。
  3. 在 [ 建立事件訂閱] 頁面上,輸入事件訂閱 的名稱 值。
  4. 對於端點類型,選擇服務匯流排佇列
  5. 選擇 選擇端點,然後選擇你之前建立的 Service Bus 佇列實例。

使用 Azure 事件格網 (Azure Event Grid) 傳送事件,並透過 Azure 服務匯流排佇列 (Azure Service Bus Queue) 接收事件。

使用 Azure Event Grid 資源,你可以使用 Spring Cloud Azure Event Grid 發送事件。 使用 Azure Service Bus Queue 資源作為事件處理程序,你可以使用 Spring Cloud Azure Stream Binder for Service Bus 接收事件。

要安裝 Spring Cloud Azure Event Grid Starter 模組和 Spring Cloud Azure Stream Binder Service Bus 模組,請在你的 pom.xml 檔案中新增以下相依關係:

  • Spring Cloud Azure 物料清單(BOM):

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.azure.spring</groupId>
          <artifactId>spring-cloud-azure-dependencies</artifactId>
          <version>7.1.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    

    注意

    如果你用的是 Spring Boot 4.0.x,記得把版本設 spring-cloud-azure-dependencies7.1.0.

    如果你用的是 Spring Boot 3.5.x,記得把版本設 spring-cloud-azure-dependencies6.1.0

    如果你使用的是 Spring Boot 3.1.x-3.5.x,記得把版本設 spring-cloud-azure-dependencies5.25.0.

    如果您使用 Spring Boot 2.x,請務必將 spring-cloud-azure-dependencies 版本設定為 4.20.0

    此材料帳單 (BOM) 應該在 <dependencyManagement> 檔案的 區段中設定。 這確保所有 Spring Cloud Azure 相依性都使用相同的版本。

    欲了解更多關於本物料清單所用版本的資訊,請參見 Spring Cloud Azure 應該使用哪個版本

  • Spring Cloud Azure 事件網格啟動器構件。

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-eventgrid</artifactId>
    </dependency>
    
  • Spring Cloud Azure Stream Binder Service Bus 工件:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-stream-binder-servicebus</artifactId>
    </dependency>
    

撰寫應用程式程序代碼

請依照以下步驟設定您的應用程式,透過 Event Grid 傳送事件,並透過 Service Bus Queue 接收事件。

  1. 請在 application.yaml 設定檔中設定Azure Event Grid與Service Bus憑證,如下範例所示:

    spring:
      cloud:
        azure:
          eventgrid:
            endpoint: ${AZURE_EVENTGRID_ENDPOINT}
            key: ${AZURE_EVENTGRID_KEY}
          servicebus:
            connection-string: ${AZURE_SERVICEBUS_CONNECTION_STRING}
        function:
          definition: consume
        stream:
          bindings:
            consume-in-0:
              destination: ${AZURE_SERVICEBUS_QUEUE_NAME}
          servicebus:
            bindings:
              consume-in-0:
                consumer:
                  auto-complete: false
    

    注意

    Microsoft 建議您使用最安全的可用驗證流程。 此程式中所述的驗證流程,例如資料庫、快取、傳訊或 AI 服務,在應用程式中需要高度的信任,而且不會在其他流程中帶來風險。 只有在更安全的選項(如用於無密碼或無密鑰連線的受控識別)不可行的情況下,才能使用此流程。 針對本機計算機作業,偏好使用無密碼或無密鑰連線的使用者身分識別。

  2. 編輯啟動類別檔案以顯示下列內容。 此程式代碼會生成補全。

    import com.azure.core.util.BinaryData;
    import com.azure.messaging.eventgrid.EventGridEvent;
    import com.azure.messaging.eventgrid.EventGridPublisherClient;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.Bean;
    import org.springframework.messaging.Message;
    
    import java.util.List;
    import java.util.function.Consumer;
    
    @SpringBootApplication
    public class EventGridSampleApplication implements CommandLineRunner {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(EventGridSampleApplication.class);
    
        @Autowired
        EventGridPublisherClient<EventGridEvent> client;
    
        public static void main(String[] args) {
            SpringApplication.run(EventGridSampleApplication.class, args);
        }
    
        @Bean
        public Consumer<Message<String>> consume() {
            return message -> {
                List<EventGridEvent> eventData = EventGridEvent.fromString(message.getPayload());
                eventData.forEach(event -> {
                    LOGGER.info("New event received: '{}'", event.getData());
                });
            };
        }
    
        @Override
        public void run(String... args) throws Exception {
            String str = "FirstName: John, LastName: James";
            EventGridEvent event = new EventGridEvent("A user is created", "User.Created.Text", BinaryData.fromObject(str), "0.1");
    
            client.sendEvent(event);
            LOGGER.info("New event published: '{}'", event.getData());
        }
    }
    
    
  3. 啟動應用程式。 啟動之後,應用程式會產生類似下列範例的記錄:

    New event published: '"FirstName: John, LastName: James"'
    ...
    New event received: '"FirstName: John, LastName: James"'
    

部署至 Azure Spring Apps

現在您已在本機執行 Spring Boot 應用程式,現在可以將其移至生產環境。 Azure Spring Apps 讓 Spring Boot 應用程式部署到 Azure 變得簡單,無需修改程式碼。 服務會管理 Spring 應用程式的基礎結構,讓開發人員能夠專注於其程式代碼。 Azure Spring Apps 提供生命週期管理,包含全面的監控與診斷、組態管理、服務發現、CI/CD 整合、藍綠部署等多項功能。 要將您的應用程式部署到 Azure Spring Apps,請參見 將您的第一個應用程式部署至 Azure Spring Apps

後續步驟

想了解更多關於 Spring 和 Azure 的資訊,請繼續閱讀 Spring on Azure 文件中心。