共用方式為


在 Spring 中使用 Azure 事件方格

本文說明如何使用 Azure 事件方格將事件傳送至主題,並使用服務總線佇列作為 事件處理程式 ,以在 Spring Boot 應用程式中接收。

Azure 事件方格服務是可高度擴充且完全受控的 Pub 子訊息散發服務,可使用 MQTT 和 HTTP 通訊協定提供彈性的訊息取用模式。

先決條件

訂閱自定義主題

使用下列步驟建立事件訂用帳戶,以告訴事件方格將事件傳送至服務總線佇列:

  1. 在 Azure 入口網站中,流覽至您的事件方格主題實例。
  2. 選取工具列上的 [事件訂閱 ]。
  3. 在 [ 建立事件訂閱] 頁面上,輸入事件訂閱 的名稱 值。
  4. 針對 [端點類型],選取 [服務總線佇列]。
  5. 選擇 [選取端點] ,然後選取您稍早建立的服務總線佇列實例。

依 Azure 事件方格傳送事件,並由 Azure 服務總線佇列接收

使用 Azure 事件方格資源,您可以使用 Spring Cloud Azure 事件方格傳送事件。 使用 Azure 服務總線佇列資源作為事件處理程式,您可以使用適用於服務總線的 Spring Cloud Azure Stream Binder 來接收事件。

若要安裝 Spring Cloud Azure 事件方格入門模組和 Spring Cloud Azure Stream Binder 服務總線模組,請將下列相依性新增至 您的pom.xml 檔案:

  • Spring Cloud Azure 材料帳單(BOM):

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

    注意

    如果您使用的是 Spring Boot 3.0.x-3.4.x,請務必將版本設定 spring-cloud-azure-dependencies5.23.0

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

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

    如需此 BOM 所用版本的詳細資訊,請參閱 應該使用哪個版本的 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 服務總線成品:

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

撰寫應用程式程序代碼

使用下列步驟來設定應用程式,以使用事件方格傳送事件,並使用服務總線佇列接收。

  1. application.yaml 組態檔中設定 Azure 事件方格和服務總線認證,如下列範例所示:

    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,請繼續前往 Azure 上的 Spring 檔中心。