在 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 事件方格 Starter 模組和 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>5.17.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    

    注意

    如果您使用 Spring Boot 2.x,請務必將 spring-cloud-azure-dependencies 版本設定為 4.19.0。 此材料帳單 (BOM) 應該在<dependencyManagement>pom.xml檔案的 區段中設定。 這可確保所有 Spring Cloud Azure 相依性都使用相同的版本。 如需此 BOM 所用版本的詳細資訊,請參閱 應該使用哪個版本的 Spring Cloud Azure。

  • Spring Cloud Azure 事件方格 Starter 成品:

    <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
    
  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 應用程式提供生命週期管理,使用全方位的監視和診斷、組態管理、服務探索、持續整合與持續傳遞的整合、藍綠部署等等。 若要將應用程式部署至 Azure Spring Apps,請參閱 將第一個應用程式部署至 Azure Spring Apps

下一步

若要深入了解 Spring 和 Azure,請繼續閱讀「Azure 上的 Spring」文件中心中的資訊。