Share via


Spring で Azure Event Grid を使用する

この記事では、Azure Event Grid を使用してトピックにイベントを送信し、Service Bus キューを イベント ハンドラー として使用して Spring Boot アプリケーションで受信する方法について説明します。

Azure Event Grid サービスは、MQTT プロトコルと HTTP プロトコルを使用した柔軟なメッセージ消費パターンを提供する、拡張性の高いフル マネージドの Pub Sub メッセージ配信サービスです。

前提条件

カスタム トピックのサブスクライブ

Service Bus Queue にイベントを送信するように Event Grid に指示するイベント サブスクリプションを作成するには、次の手順を実行します。

  1. Azure Portal で、Event Grid トピック インスタンスに移動します。
  2. ツール バーの [イベント サブスクリプション] を選択します。
  3. [イベント サブスクリプションを作成] ページで、イベント サブスクリプションの名前の値を入力します。
  4. [エンドポイントの種類] で、[Service Bus Queue] を選択します。
  5. [エンドポイントをの選択] を選択し、前に作成した Service Bus Queue インスタンスを選択します。

Azure Event Grid でイベントを送信し、Azure Service Bus Queue で受信する

Azure Event Grid リソースでは、Spring Cloud Azure Event Grid を使用してイベントを送信できます。 イベント ハンドラーとして Azure Service Bus Queue リソースを使用すると、Service Bus 用 Spring Cloud Azure Stream Binder を使用してイベントを受信できます。

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>5.12.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    

    Note

    Spring Boot 2.xを使用している場合は、 spring-cloud-azure-dependencies バージョンを 4.18.0に設定してください。 この部品表(BOM)は、 pom.xml ファイルの <dependencyManagement> セクションで設定する必要があります。 これにより、すべてのSpring Cloud Azure依存関係が同じバージョンを使用していることが保証されます。 このBOMに使用されるバージョンの詳細については、「Spring Cloud Azureのどのバージョンを使うべきか」を参照してください。

  • Spring Cloud Azure Event Grid Starter アーティファクト:

    <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
    
  2. スタートアップ クラス ファイルを編集して、次の内容を表示します。 このコードは Completion を生成します。

    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 に関するドキュメントをご確認ください。