Spring Session + Redis

今回は、RedisをSessionを保存する方法についてみていきたいともいます。自分が理解している範囲での記事なので間違っているところがある可能性があります。

サンプルコードを見ながら解説していきたいと思います。

RedisConfig作成

@RequiredArgsConstructor
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)
public class SessionConfig extends AbstractHttpSessionApplicationInitializer {

  @Value("${spring.redis.host}")
  private String host;

  @Value("${spring.redis.port}")
  private Integer port;

  @Value("${spring.redis.password}")
  private String password;

  private final ObjectMapper objectMapper;

  @Bean
  public RedisConnectionFactory lettuceConnectionFactory() {
    RedisStandaloneConfiguration standaloneConfiguration = new RedisStandaloneConfiguration(host, port);
    standaloneConfiguration.setPassword(RedisPassword.of(password));
    return new LettuceConnectionFactory(standaloneConfiguration);
  }

  @Bean
  public RedisTemplate<String, Object> redisTemplate() {
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

    redisTemplate.setConnectionFactory(lettuceConnectionFactory()); 
    redisTemplate.setEnableTransactionSupport(true);
    redisTemplate.setKeySerializer(new StringRedisSerializer()); 
    redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));

    return redisTemplate;
  }
}
  • @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)
    • Redisにセッションデータを保存するためにはこのアノテーションを付与する必要があります。
    • maxInactiveIntervalInSeconds:セッションの有効期間を秒単位で設定します。デフォルトは「1800(30分)」です。
    • RedisIndexedSessionRepositoryを作成してくれます。
  • AbstractHttpSessionApplicationInitializer
    • pringがJavaConfigを読み込むことを保証する仕組みを提供するクラスです。
  • lettuceConnectionFactory()
    • Redisに接続するために実装を行います。
    • ホストやパスワードをセットします。
    • LettuceConnectionFactory:Spring Data RedisによってサポートされるNettyベースのオープンソースコネクタです。
  • RedisTemplate
    • Redis Commandを手伝ってくれます。
    • RedisサーバーへRedisコマンドを実行するためのHigh -Level -Abstractionsを提供します。
    • ObjectのSerializable、Connection Managementを行います。
    • Tread -Safeであり、再利用が可能です。
  • redisTemplate()
    • setConnectionFactory():接続ファクトリを設定します。
    • setEnableTransactionSupport(true):trueを設定することでRedisTemplateは作業を追跡するために「MULTI…EXEC|DISCARD」を使って現在のトランザクションに参加します。
    • setKeySerializer():このテンプレートで使用されるキーシリアルライザーを設定します。
    • setValueSerializer():このテンプレートで使用される値のシリアルライザーを設定します。

プロパティ設定

spring:
    redis:
    host: 127.0.0.1
    port: 6379
    password: your password
  session:
    store-type: redis
  • session.flush-modeも設定できますが、デフォルトは「on-save」です。
    • on-save:呼び出される時のみRedisに記録を行う。
    • immediate;即時Redisに記録を行う。

DockerでRedisを起動(追加)

Redisをインストールして使用することも可能ですが、自分はDockerを利用します。

docker-compose.yml

version: "3"
services:
  redis1:
    image: redis
    container_name: redis1
    command: redis-server --requirepass root --port 6379
    restart: always
    ports:
      - 6379:6379

docker-compose.ymlのパスへ移動します。

cd パス

redisを起動します。

docker-compose up -d

コンテナに接続します。

docker exec -it コンテナ名 bash

redis-cliに接続します。(ポートを指定することも可能です。)

redis-cli
redis-cli -p 6379

Redisパスワードを入力します。(初期は「root」)

パスワードを入力しないとコマンドができないです。

auth root

オブジェクトを確認します。

keys *

「Spring Session + Redis」への1件のフィードバック

コメントを残す