次の方法で共有


SpringアプリケーションでAzure Storage Queueを使用

この記事では、Spring Frameworkで構築されたJavaアプリケーションでAzure Storage Queueを使用する方法について説明します。

Azure Storage Queueはクラウドベースのキューを実装し、分散アプリケーションのコンポーネント間の通信を可能にします。 各キューには、送信側コンポーネントにより追加し、受信側コンポーネントにより処理できるメッセージの一覧が保持されます。 キューを利用することで、アプリケーションを需要に合わせてすぐにスケーリングできます。

Spring Cloud Azureには、Spring Frameworkを使用してAzure Storage Queueにメッセージを送受信するためのさまざまなモジュールが用意されています。 次のリストで説明するように、これらのモジュールは個別に使用することも、さまざまなユースケースに組み合せることもできます。

前提条件

  • Azure StorageアカウントとAzure Queue。 これらのリソースがない場合は、まずストレージアカウントを作成し、次にキューを作成します。 詳細については、Quickstartの「ストレージアカウントを作成」および「キューを作成」セクションを参照してください。Azureポータルでキューを作成し、メッセージを追加します。

  • Spring Boot アプリケーション。 ない場合は、Spring Initializr で Maven プロジェクトを作成します。 必ず、 [Maven プロジェクト] を選択し、 [依存関係][Spring Web] 依存関係を追加してから、Java のバージョン 8 以降を選択してください。

アカウント アクセス権をリソースに付与するには、新規作成された Azure Storage アカウントで、Storage Queue Data Contributor ロールを、現在使用している Microsoft Entra アカウントに割り当てます。 詳細については、 Azure portal を使用して Azure ロールを割り当てる方法に関するページを参照してください。

重要

このチュートリアルの手順を完了するには、Spring Boot 2.5 以上のバージョンが必要です。

ローカル環境を準備する

このチュートリアルでは、コンフィギュレーションとコードには認証操作がありません。 ただし、Azureサービスに接続するには認証が必要です。 認証を完了するには、Azure Identityクライアントライブラリを使用する必要があります。 Spring Cloud Azure では、 DefaultAzureCredentialを使用します。これは、コードを変更せずに資格情報を取得できるようにするために、Azure ID ライブラリで提供されます。

DefaultAzureCredential は複数の認証方法をサポートしており、実行時に使用する方法が決定されます。 このアプローチは、環境固有のコードを実装することなく、アプリが異なる環境(ローカル環境や本番環境など)で異なる認証方法を使用することを可能にします。 詳細については、 Authenticate Azure-hosted Javaアプリケーション の「DefaultAzureCredential」セクションを参照してください。

Azure CLI、IntelliJ、またはその他の方法を使用してローカル開発環境で認証を完了する方法については、 Java開発環境でのAzure認証を参照してください。 Azureホスティング環境で認証を完了するには、管理されたIDを使用することを推奨します。 詳細については、「Azure リソースのマネージド ID とは」を参照してください。

Spring Cloud Azure Storage Queue Starterを使用

Spring Cloud Azure Storage Queue Starterモジュールは、Spring Bootフレームワークを使用してJava用のAzure Storage Queueクライアントライブラリをインポートします。 Spring Cloud AzureとAzure SDKを相互排他的でないパターンで一緒に使用することができます。 したがって、SpringアプリケーションでStorage Queue JavaクライアントAPIを使用し続けることができます。

依存関係を追加する

Spring Cloud Azure Storage Queue Starterモジュールをインストールするには、次の依存関係をpom.xmlファイルに追加します。

  • Spring Cloud Azure 部品表 (BOM):

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

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

  • Spring Cloud Azure Queue Storage Queueアーティファクト:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-storage-queue</artifactId>
    </dependency>
    

アプリケーションをコード化してメッセージの送受信を行う

ここでは、SpringアプリケーションのコンテキストでAzure Queue Storageクライアントを使用する方法について説明します。 次の2つのオプションがあります。

  • Spring Boot自動設定を使用し、Springコンテキストからすぐに使用できるクライアントを使用します(推奨)。
  • クライアントをプログラム的に構築します。

自動設定を使用すると、Spring制御の反転(IoC)コンテナからクライアントBeanを自動的に配線できます。 このアプローチにより、Storage Queueクライアントを使用して開発する際の柔軟性と効率性が向上します。 自動設定には、次の利点があります。

  • 自動設定では、異なる環境で同じアプリケーション コードを使用できるように、外部コンフィギュレーションが使用されます。

  • ビルダパターンを学習し、クライアントをアプリケーションコンテキストに登録するプロセスをSpring Bootフレームワークに委任できます。 自身のビジネス要件を満たすクライアントの使用方法のみに焦点を当てています。

  • ヘルスインジケータを使用して、アプリケーションおよび内部コンポーネントのステータスとヘルスを検査できます。

次のセクションのコード例は、説明されている2つの代替方法でQueueClientを使用する方法を示しています。

ヒント

Azure Java SDK for Storage Queueは、複数のクライアントがStorage Queueと対話できるようにします。 また、スターターはすべてのStorage Queueクライアントとクライアントビルダに自動設定を提供します。 この記事では、例としてQueueClientのみを使用しています。

Spring Boot Autoconfigurationを使用

Azure Storageキューとの間でメッセージを送受信するには、次の手順に従ってアプリケーションを設定します。

  1. 次の例に示すように、ストレージアカウント名とキュー名を設定します。

    spring.cloud.azure.storage.queue.account-name=<your-storage-account-name>
    spring.cloud.azure.storage.queue.queue-name=<your-storage-queue-name>
    
  2. 次の例に示すように、SpringアプリケーションにQueueClientを挿入し、関連するAPIを呼び出してメッセージを送信します。

    import com.azure.storage.queue.QueueClient;
    import com.azure.storage.queue.models.QueueMessageItem;
    import com.azure.storage.queue.models.SendMessageResult;
    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;
    
    @SpringBootApplication
    public class StorageQueueClientApplication implements CommandLineRunner {
    
        private final static Logger logger = LoggerFactory.getLogger(StorageQueueClientApplication.class);
    
        @Autowired
        private QueueClient queueClient;
    
        public static void main(String[] args) {
            SpringApplication.run(StorageQueueClientApplication.class, args);
        }
    
        @Override
        public void run(String... args) {
         // Using the QueueClient object, call the create method to create the queue in your storage account.
            queueClient.create();
            SendMessageResult sendMessageResult = queueClient.sendMessage("Hello world");
            logger.info("Send message id: {}", sendMessageResult.getMessageId());
    
            QueueMessageItem queueMessageItem = queueClient.receiveMessage();
            logger.info("Received message: {}", new String(queueMessageItem.getBody().toBytes()));
        }
    
    }
    
  3. アプリケーションを起動します。 起動後、アプリケーションは次の例のようなログを生成します。

    Send message id: ...
    Received message: Hello world
    

クライアントをプログラム的に構築します

クライアントBeansは自分で作成できますが、プロセスは複雑です。 Spring Boot アプリケーションでは、プロパティを管理し、ビルダパターンを学習し、Spring アプリケーション コンテキストにクライアントを登録する必要があります。 次の手順は、その方法を示しています。

  1. 次の例に示すように、Springアプリケーションでプログラム的にクライアントを構築します。 <storage-account-name>プレースホルダを自分の値で置き換えるようにしてください。

    import com.azure.identity.DefaultAzureCredentialBuilder;
    import com.azure.storage.queue.QueueClient;
    import com.azure.storage.queue.QueueClientBuilder;
    import com.azure.storage.queue.models.QueueMessageItem;
    import com.azure.storage.queue.models.SendMessageResult;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class StorageQueueClientApplication implements CommandLineRunner {
    
        private final static String queueName = "test-queue";
        private final static String endpoint = "https://<storage-account-name>.queue.core.windows.net/";
        private final static Logger logger = LoggerFactory.getLogger(StorageQueueClientApplication.class);
    
        QueueClient queueClient = new QueueClientBuilder()
            .endpoint(endpoint)
            .queueName(queueName)
            .credential(new DefaultAzureCredentialBuilder().build())
            .buildClient();
    
        public static void main(String[] args) {
            SpringApplication.run(StorageQueueClientApplication.class, args);
        }
    
        @Override
        public void run(String... args) {
         // Using the QueueClient object, call the create method to create the queue in your storage account.
            queueClient.create();
            SendMessageResult sendMessageResult = queueClient.sendMessage("Hello world");
            logger.info("Send message id: {}", sendMessageResult.getMessageId());
    
            QueueMessageItem queueMessageItem = queueClient.receiveMessage();
            logger.info("Received message: {}", new String(queueMessageItem.getBody().toBytes()));
        }
    
    }
    
  2. アプリケーションを起動します。 起動後、アプリケーションは次の例のようなログを生成します。

    Send message id: ...
    Received message: Hello world
    

次のリストは、このコードが柔軟でないかグレースフルでない理由を示しています。

  • ストレージアカウントとキュー名は、ハードコードされています。
  • Spring 環境から構成を取得するために @Value を使用する場合、 application.properties ファイルに IDE ヒントを含めることはできません。
  • マイクロサービスのシナリオがある場合は、各プロジェクトでコードを複製する必要があります。また、エラーが発生しやすく、一貫性を保つのが困難です。

幸いなことに、Spring Cloud AzureではクライアントBeansを自分で構築する必要はありません。 代わりに、これらを直接注入して、すでに慣れている構成プロパティを使用してストレージキューを構成することができます。 詳細については、Spring Cloud Azureの構成プロパティを参照してください。

Spring Cloud Azure には、さまざまなシナリオに対して次のグローバル構成も用意されています。 詳細については、Spring Cloud Azureのグローバルコンフィギュレーションプロパティを参照してください。

  • プロキシ オプション。
  • 再試行オプション。

別の Azure クラウドに接続することもできます。 詳細については、 「さまざまなAzureクラウドへの接続」を参照してください。

Spring Messaging Azure Storage Queueを使用

Spring Messaging Azure Storage Queueモジュールは、Azure Queue Storageを使用したSpring Messagingフレームワークをサポートします。

Spring Messaging Azure Storage Queueを使用している場合は、StorageQueueTemplate機能を使用してストレージキューに非同期および同期的にメッセージを送信できます。

ここでは、Spring Messaging Azure Storage Queueを使用して、ストレージキューとの間でメッセージを送受信する方法について説明します。

依存関係を追加する

Spring Messaging Azure Storage Queueモジュールをインストールするには、次の依存関係をpom.xmlファイルに追加します。

  • Spring Cloud Azure 部品表 (BOM):

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

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

  • Spring Cloud Azure のスターターと Spring Messaging Storage Queue のアーティファクト:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter</artifactId>
    </dependency>
    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-messaging-azure-storage-queue</artifactId>
    </dependency>
    

アプリケーションをコード化してメッセージの送受信を行う

次の手順に従って、アプリケーションを設定およびコード化します。

  1. 次の例に示すように、ストレージキューのAzure Storageアカウント名を設定します。

    spring.cloud.azure.storage.queue.account-name=<your-storage-account-name>
    
  2. 次の例に示すように、Springでメッセージを送受信するために、送信者と受信者を有線で接続します。 <storage-queue-name>プレースホルダを自分の値で置き換えるようにしてください。

    import com.azure.spring.messaging.AzureHeaders;
    import com.azure.spring.messaging.checkpoint.Checkpointer;
    import com.azure.spring.messaging.storage.queue.core.StorageQueueTemplate;
    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.messaging.Message;
    import org.springframework.messaging.support.MessageBuilder;
    import java.time.Duration;
    
    @SpringBootApplication
    public class StorageQueueMessagingApplication implements CommandLineRunner {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(StorageQueueMessagingApplication.class);
        private static final String STORAGE_QUEUE_NAME = "<storage-queue-name>";
    
        @Autowired
        StorageQueueTemplate storageQueueTemplate;
    
        public static void main(String[] args) {
            SpringApplication.run(StorageQueueMessagingApplication.class, args);
        }
    
        @Override
        public void run(String... args) {
            storageQueueTemplate
                .sendAsync(STORAGE_QUEUE_NAME, MessageBuilder.withPayload("Hello world").build())
                .subscribe();
            LOGGER.info("Message was sent successfully.");
    
            Message<?> message = storageQueueTemplate.receiveAsync(STORAGE_QUEUE_NAME, Duration.ofSeconds(30)).block();
            LOGGER.info("Received message: {}", new String((byte[]) message.getPayload()));
        }
    
    }
    
  3. アプリケーションを起動します。 起動後、アプリケーションは次の例のようなログを生成します。

    Message was sent successfully.
    ...
    Received message: Hello World
    

Spring Integration Azure Storage Queueを使用

Spring Integration Azure Storage Queueモジュールは、ストレージキューを含むSpring Integrationフレームワークをサポートします。

SpringアプリケーションがSpring Integrationメッセージチャネルを使用している場合は、チャネルアダプタを使用してメッセージチャネルとストレージキュー間でメッセージをルーティングできます。 インバウンドチャネルアダプタは、ストレージキューからのメッセージをメッセージチャネルに転送します。 アウトバウンドチャネルアダプタは、メッセージチャネルからストレージキューにメッセージをパブリッシュします。

ここでは、Spring Integration Azure Storage Queueを使用して、ストレージキューとの間でメッセージを送受信する方法について説明します。

依存関係を追加する

Spring Integration Azure Storage Queueモジュールをインストールするには、次の依存関係をpom.xmlファイルに追加します。

  • Spring Cloud Azure 部品表 (BOM):

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

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

  • Spring IntegrationのAzureストレージキューアーティファクト:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-integration-storage-queue</artifactId>
    </dependency>
    

アプリケーションをコード化してメッセージの送受信を行う

次の手順に従って、アプリケーションを設定およびコード化します。

  1. ストレージキューのAzure Storageアカウント名を設定します。

    spring.cloud.azure.storage.queue.account-name=<your-storage-account-name>
    
  2. 次の例で示すように、新しい QueueReceiveConfiguration Java クラスを作成します。 このクラスは、メッセージ受信者を定義するために使用されます。 <storage-queue-name>プレースホルダを自分の値で置き換えるようにしてください。

    import com.azure.spring.integration.storage.queue.inbound.StorageQueueMessageSource;
    import com.azure.spring.messaging.AzureHeaders;
    import com.azure.spring.messaging.checkpoint.Checkpointer;
    import com.azure.spring.messaging.storage.queue.core.StorageQueueTemplate;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.integration.annotation.InboundChannelAdapter;
    import org.springframework.integration.annotation.Poller;
    import org.springframework.integration.annotation.ServiceActivator;
    import org.springframework.messaging.handler.annotation.Header;
    
    @Configuration
    public class QueueReceiveConfiguration {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(QueueReceiveConfiguration.class);
        private static final String STORAGE_QUEUE_NAME = "<storage-queue-name>";
        private static final String INPUT_CHANNEL = "input";
    
        @Bean
        @InboundChannelAdapter(channel = INPUT_CHANNEL, poller = @Poller(fixedDelay = "1000"))
        public StorageQueueMessageSource storageQueueMessageSource(StorageQueueTemplate storageQueueTemplate) {
            return new StorageQueueMessageSource(STORAGE_QUEUE_NAME, storageQueueTemplate);
        }
    
        @ServiceActivator(inputChannel = INPUT_CHANNEL)
        public void messageReceiver(byte[] payload, @Header(AzureHeaders.CHECKPOINTER) Checkpointer checkpointer) {
            String message = new String(payload);
            LOGGER.info("Received message: {}", message);
        }
    
    }
    
  3. 次の例で示すように、新しい QueueSendConfiguration Java クラスを作成します。 このクラスは、メッセージ送信者を定義するために使用されます。 <storage-queue-name>プレースホルダを自分の値で置き換えるようにしてください。

    import com.azure.spring.integration.core.handler.DefaultMessageHandler;
    import com.azure.spring.messaging.storage.queue.core.StorageQueueTemplate;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.integration.annotation.MessagingGateway;
    import org.springframework.integration.annotation.ServiceActivator;
    import org.springframework.messaging.MessageHandler;
    import org.springframework.util.concurrent.ListenableFutureCallback;
    
    @Configuration
    public class QueueSendConfiguration {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(QueueSendConfiguration.class);
        private static final String STORAGE_QUEUE_NAME = "<storage-queue-name>";
        private static final String OUTPUT_CHANNEL = "output";
    
        @Bean
        @ServiceActivator(inputChannel = OUTPUT_CHANNEL)
        public MessageHandler messageSender(StorageQueueTemplate storageQueueTemplate) {
            DefaultMessageHandler handler = new DefaultMessageHandler(STORAGE_QUEUE_NAME, storageQueueTemplate);
            handler.setSendCallback(new ListenableFutureCallback<Void>() {
                @Override
                public void onSuccess(Void result) {
                    LOGGER.info("Message was sent successfully.");
                }
    
                @Override
                public void onFailure(Throwable ex) {
                    LOGGER.info("There was an error sending the message.");
                }
            });
            return handler;
        }
    
        @MessagingGateway(defaultRequestChannel = OUTPUT_CHANNEL)
        public interface StorageQueueOutboundGateway {
            void send(String text);
        }
    
    }
    
  4. Springでメッセージを送受信するために、送信者と受信者を有線で接続します。

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.integration.config.EnableIntegration;
    
    @SpringBootApplication
    @EnableIntegration
    @Configuration(proxyBeanMethods = false)
    public class StorageQueueIntegrationApplication {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext applicationContext = SpringApplication.run(StorageQueueIntegrationApplication.class, args);
            QueueSendConfiguration.StorageQueueOutboundGateway storageQueueOutboundGateway = applicationContext.getBeanQueueSendConfiguration.StorageQueueOutboundGateway.class);
            storageQueueOutboundGateway.send("Hello World");
        }
    
    }
    

    ヒント

    Spring Integrationインフラストラクチャを有効にする@EnableIntegration注釈を追加することを忘れないでください。

  5. アプリケーションを起動します。 起動後、アプリケーションは次の例のようなログを生成します。

    Message was sent successfully.
    Received message: Hello World
    

Azure Spring Apps にデプロイする

Spring Boot アプリケーションがローカルで実行されたので、運用環境に移行します。 Azure Spring Apps では、コードを変更せずに、Spring Boot アプリケーションを Azure に簡単にデプロイできます。 Spring アプリケーションのインフラストラクチャはこのサービスによって管理されるため、開発者はコードに専念できます。 Azure Spring Apps では、包括的な監視と診断、構成管理、サービス検出、CI/CD 統合、ブルー/グリーン デプロイなどを使用して、ライフサイクルを管理できます。 Azure Spring Apps にアプリケーションをデプロイするには、「初めてのアプリケーションを Azure Spring Apps にデプロイする」を参照してください。

次のステップ

関連項目

Microsoft Azureで利用可能なSpring Boot Starterの詳細については、「Spring Cloud Azureとは?」を参照してください