次の方法で共有


Spring で Azure Redis Cache を使用する

Azure Cache for Redis は、Redis ソフトウェアをベースにしたメモリ内データストアを提供します。 Redis では、バックエンドのデータ ストアを多用するアプリケーションのパフォーマンスとスケーラビリティを高めることができます。

このチュートリアルでは、Redis Cache を使用して Spring Boot アプリケーションにデータを格納および取得する方法について説明します。

このチュートリアルには、Microsoft Entra 認証と Redis 認証の 2 つの認証方法が含まれています。 [パスワードレス] タブには Microsoft Entra 認証が表示され、[パスワード] タブには Redis 認証が表示されます。

Microsoft Entra 認証は、Microsoft Entra ID で定義された ID を使用して Azure Cache for Redis に接続するための仕組みです。 Microsoft Entra 認証を使用すると、データベース ユーザーの ID や他の Microsoft サービスを一元管理でき、アクセス許可の管理が容易になります。

Redis 認証では、Redis でパスワードが使用されます。 資格情報としてパスワードを使用する場合は、自分でパスワードを管理する必要があります。

前提条件

Azure Cache for Redis へのデータのキャッシュ

Azure Cache for Redis インスタンスを使用すると、Spring Cloud Azure を使用してデータをキャッシュできます。

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

<dependencies>
 <dependency>
   <groupId>com.azure.spring</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 <dependency>
   <groupId>com.azure.spring</groupId>
   <artifactId>spring-cloud-azure-starter-data-redis-lettuce</artifactId>
 </dependency>
 <dependency>
   <groupId>com.azure.spring</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
 </dependency>
</dependencies>

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

Note

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

アプリケーションをコーディングする

Redis Cache を使用してデータを格納および取得するには、次の手順を実行してアプリケーションを構成します。

  1. 次の例に示すように、application.properties 構成ファイルで Redis Cache 資格情報を構成します。

    spring.data.redis.host=<your-redis-name>.redis.cache.windows.net
    spring.data.redis.port=6380
    spring.data.redis.username=<your-redis-username>
    spring.data.redis.ssl.enabled=true
    spring.data.redis.azure.passwordless-enabled=true
    

    Note

    username の値を取得するには、「キャッシュ認証に Microsoft Entra ID を使用する」の「キャッシュで Microsoft Entra ID 認証を有効にする」セクションの手順に従って、username 値をコピーします。

  2. スタートアップ クラス ファイルを編集して、次の内容を表示します。 このコードは、データを格納および取得します。

    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.data.redis.core.StringRedisTemplate;
    import org.springframework.data.redis.core.ValueOperations;
    
    @SpringBootApplication
    public class DemoCacheApplication implements CommandLineRunner {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(DemoCacheApplication.class);
    
        @Autowired
        private StringRedisTemplate template;
    
        public static void main(String[] args) {
            SpringApplication.run(DemoCacheApplication.class, args);
        }
    
        @Override
        public void run(String... args) {
            ValueOperations<String, String> ops = this.template.opsForValue();
            String key = "testkey";
            if(!this.template.hasKey(key)){
                ops.set(key, "Hello World");
                LOGGER.info("Add a key is done");
            }
            LOGGER.info("Return the value from the cache: {}", ops.get(key));
        }
    
    }
    

次に、アプリケーションを起動します。 アプリケーションは Redis Cache からデータを取得します。 次の例のようなログが表示されます。

Add a key is done
Return the value from the cache: 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 にデプロイする」を参照してください。

次のステップ

Spring および Azure の詳細については、Azure ドキュメント センターで引き続き Spring に関するドキュメントをご確認ください。