演習 - Spring Data Redis を使用する Spring Boot アプリケーションを作成する

完了

このユニットでは、Spring Data Redis を使用して Azure Cache for Redis のデータを格納および取得する Spring Boot アプリケーションを作成します。 Azure Cache for Redis インスタンスのデプロイが完了するまで待機している間、Azure Cache for Redis への最終的な接続を除き、アプリケーションを作成できます。

Spring Boot プロジェクトを作成する

Spring Boot プロジェクトを作成するには、次の Spring Initializr コマンド ラインを実行します。

curl https://start.spring.io/starter.tgz -d type=maven-project -d dependencies=web,data-redis -d baseDir=spring-redis-application -d bootVersion=2.4.1.RELEASE -d javaVersion=1.8 | tar -xzvf -

このコマンドでは、 Spring Web コンポーネントと Spring Data Redis コンポーネントが使用されます。 Spring Data RedisLettuce Redis ドライバーを使用します。これは、より高度なタスクにも使用できます。

Spring コードを追加してデータを管理する

  1. Spring Boot プロジェクトの DemoApplication クラスの横に、次のように Todo ドメイン オブジェクトを追加します。

    package com.example.demo;
    
    import org.springframework.data.annotation.Id;
    import org.springframework.data.redis.core.RedisHash;
    
    import java.io.Serializable;
    
    @RedisHash("Todo")
    public class Todo implements Serializable {
    
        public Todo() {
        }
    
        public Todo(String description, String details, boolean done) {
            this.description = description;
            this.details = details;
            this.done = done;
        }
    
        @Id
        private Long id;
    
        private String description;
    
        private String details;
    
        private boolean done;
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    
        public String getDetails() {
            return details;
        }
    
        public void setDetails(String details) {
            this.details = details;
        }
    
        public boolean isDone() {
            return done;
        }
    
        public void setDone(boolean done) {
            this.done = done;
        }
    }
    
  2. 次のように、このコレクションを管理するために 、TodoRepository という Spring Data Redis リポジトリを作成します。

    package com.example.demo;
    
    import org.springframework.data.repository.CrudRepository;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public interface TodoRepository extends CrudRepository<Todo, String> {
    
    }
    
  3. 次のように、 TodoController という Spring MVC コントローラーを追加します。

     package com.example.demo;
    
    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.*;
    
    @RestController
    @RequestMapping("/")
    public class TodoController {
    
        private final TodoRepository todoRepository;
    
        public TodoController(TodoRepository todoRepository) {
            this.todoRepository = todoRepository;
        }
    
        @PostMapping("/")
        @ResponseStatus(HttpStatus.CREATED)
        public Todo createTodo(@RequestBody Todo todo) {
            return todoRepository.save(todo);
        }
    
        @GetMapping("/")
        public Iterable<Todo> findAllTodos() {
            return todoRepository.findAll();
        }
    }
    

Azure Cache for Redis のセキュリティ キーを取得する

  1. 次のコマンドを実行して、Azure Cache for Redis インスタンスを使用する準備ができているかどうかを確認します。

    az redis show --name $AZ_REDIS_NAME --resource-group $AZ_RESOURCE_GROUP
    

    このコマンドは、 provisioningState 属性を含む JSON データを返します。 provisioningState Succeeded値がある場合、Azure Cache for Redis インスタンスは完全に使用できます。

    ヒント

    jq ユーティリティがある場合は、次の 1 つのコマンド ラインを使用して準備状況を確認できます。

    az redis show --name $AZ_REDIS_NAME --resource-group $AZ_RESOURCE_GROUP | jq '.provisioningState'
    
  2. Azure Cache for Redis インスタンスの準備ができたら、次のコマンドを実行してセキュリティ キーを取得します。

    az redis list-keys \
        --resource-group $AZ_RESOURCE_GROUP \
        --name $AZ_REDIS_NAME
    

    出力から primaryKey 値をコピーして、次の手順で使用します。

Azure Cache for Redis に接続するように Spring Boot を構成する

アプリケーションで src/main/resources/application.properties 構成ファイルを開き、次のプロパティを追加します。 <redisName>プレースホルダーを Redis インスタンス名に置き換え、<redisPrimaryKey>プレースホルダーを前の手順で取得したprimaryKey値に置き換えます。

spring.redis.host=<redisName>.redis.cache.windows.net
spring.redis.password=<redisPrimaryKey>
spring.redis.port=6380
spring.redis.ssl=true

ローカルでアプリケーションをテストする

  1. 開発環境で実行可能 な DemoApplication を実行するか、次のように Spring Boot Maven プラグインを実行して、Spring Boot アプリケーションを実行します。

    ./mvnw spring-boot:run
    
  2. アプリケーションが実行されている状態で、次のコマンドを使用して Redis にデータを格納します。

    curl -d '{"description":"a description", "details":"some details"}' -H "Content-Type: application/json" -X POST http://127.0.0.1:8080
    
  3. Redis からそのデータを取得します。

    curl http://127.0.0.1:8080
    

次のユニットに進み、Azure Cache for Redis を使用して Spring Session を介して HTTP セッション データを格納する方法について説明します。