演習 - 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 -

Note

コマンドでは、Spring Web および Spring Data Redis コンポーネントが使用されます。 Spring Data Redis では Lettuce 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 ユーティリティがある場合は、次の単一のコマンド ラインを使用して準備を確認できます。

    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 セッション データを格納する方法について学習します。