次の方法で共有


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

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

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

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

前提条件

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

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

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

重要

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

ローカル環境を準備する

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

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

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

Spring Cloud Azure Storage Queue Starter を使用する

Spring Cloud Azure Storage Queue Starter モジュールは、Spring Boot フレームワーク<>Azure Storage Java 用のキュー クライアント ライブラリをインポートします。 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>7.1.0</version>
           <type>pom</type>
           <scope>import</scope>
           </dependency>
       </dependencies>
    </dependencyManagement>
    

    Spring Boot 4.0.x を使用している場合は、必ず spring-cloud-azure-dependencies バージョンを 7.1.0 に設定してください。

    Spring Boot 3.5.x を使用している場合は、必ず spring-cloud-azure-dependencies バージョンを 6.1.0 に設定してください。

    Spring Boot 3.1.x-3.5.x を使用している場合は、必ず spring-cloud-azure-dependencies バージョンを 5.25.0 に設定してください。

    Spring Boot 2.xを使用している場合は、 spring-cloud-azure-dependencies バージョンを 4.20.0に設定してください。

    この部品表(BOM)は、<dependencyManagement> ファイルの セクションに設定する必要があります。 これにより、すべての Spring Cloud Azure依存関係で同じバージョンが使用されるようになります。

    この BOM に使用されるバージョンの詳細については、「どのバージョンの Spring Cloud Azure を使用すべきですか?」を参照してください。

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

    <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クライアントとクライアントビルダに自動設定を提供します。 この記事では、例として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では、クライアント Bean を自分で構築する必要はありません。 代わりに、これらを直接注入して、すでに慣れている構成プロパティを使用してストレージキューを構成することができます。 詳細については、「Spring Cloud Azure 構成プロパティを参照してください。

Spring Cloud Azureでは、さまざまなシナリオに対して次のグローバル構成も提供されます。 詳細については、「Spring Cloud Azureグローバル構成プロパティɳ」を参照してください。

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

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

Spring Messaging Azure Storage キューを使用する

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

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

    Spring Boot 4.0.x を使用している場合は、必ず spring-cloud-azure-dependencies バージョンを 7.1.0 に設定してください。

    Spring Boot 3.5.x を使用している場合は、必ず spring-cloud-azure-dependencies バージョンを 6.1.0 に設定してください。

    Spring Boot 3.1.x-3.5.x を使用している場合は、必ず spring-cloud-azure-dependencies バージョンを 5.25.0 に設定してください。

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

    Spring Boot 4.0.x を使用している場合は、必ず spring-cloud-azure-dependencies バージョンを 7.1.0 に設定してください。

    Spring Boot 3.5.x を使用している場合は、必ず spring-cloud-azure-dependencies バージョンを 6.1.0 に設定してください。

    Spring Boot 3.1.x-3.5.x を使用している場合は、必ず spring-cloud-azure-dependencies バージョンを 5.25.0 に設定してください。

    Spring Boot 2.xを使用している場合は、 spring-cloud-azure-dependencies バージョンを 4.20.0に設定してください。

    この部品表(BOM)は、<dependencyManagement> ファイルの セクションに設定する必要があります。 これにより、すべての Spring Cloud Azure依存関係で同じバージョンが使用されるようになります。

    この BOM に使用されるバージョンの詳細については、「どのバージョンの Spring Cloud Azure を使用すべきですか?」を参照してください。

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

    <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とは