daisuzz.log

Spring Session Data RedisがどうやってRedis Keyspace Notificationsを有効にしているのかコードを読んでみた

iikanji.hatenablog.jp

↑こちらの去年の記事で、RedisのKeyspace Notificationsについて書いたのですが、その中でSpring SessionはRedisのKeyspace Notificationsを自動で設定してくれる、と書きました。 今回は、その設定をしているConfigureNotifyKeyspaceEventsActionクラスについてどういった処理をしていて、Spring Bootではどのように設定されているのか説明します。

ConfigureNotifyKeyspaceEventsActionについて

Spring Session Data Redisでは、ConfigureRedisActionというインターフェースが定義されています。 このインターフェースは、Redisの設定を有効にしたり、Redisの検証などをおこなうためのインターフェースで、configure(RedisConnection connection)というメソッドが1つ定義されています。

ConfigureRedisAction (spring-session-docs 2.3.2.RELEASE API)

ConfigureNotifyKeyspaceEventsActionクラスは、このインターフェースの実装クラスで、Redisの現在設定されているnotify-keyspace-eventsオプションの値を確認して、Spring Sessionで利用するために必要なオプション値を設定するコマンドを実行する処理が定義されています。

ConfigureNotifyKeyspaceEventsAction (spring-session-docs 2.3.2.RELEASE API)

コマンドを実行する際には、アプリケーションで利用しているRedisのクライアントライブラリが使われるため、JedisやLettuceなどのライブラリによってRedisの設定コマンドが実行されます。

Spring Session Data Redisでは、デフォルトで、RedisHttpSessionConfigurationというクラスにConfigureNotifyKeyspaceEventsActionが設定されています。 RedisHttpSessionConfigurationクラスに定義されているEnableRedisKeyspaceNotificationsInitializerクラスのafterPropertiesSet()というメソッドによって、ConfigureRedisActionインターフェースのconfigure(RedisConnection connection)というメソッドが呼ばれRedisの設定が行われます。

RedisHttpSessionConfiguration (spring-session-docs 2.3.2.RELEASE API)

Spring Bootを利用した場合の設定

Spring Bootを利用してSpring Sessionを利用する場合、ConfigureRedisActionがどうやって設定されているかをみていきます。

Spring Bootを利用している場合は、RedisSessionConfigurationというクラスによってSpring Bootアプリケーション起動時にSpring Session Data Redis周りの設定やBeanがセットされます。

spring-boot/RedisSessionConfiguration.java at master · spring-projects/spring-boot · GitHub

RedisSessionConfigurationクラスのconfigureRedisAction(RedisSessionProperties redisSessionProperties)というメソッドによって、ConfigureRedisActionインターフェースのBeanが自動で定義されます。 @ConditionalonMissingBeanが付与されているので、アプリケーション側で独自にConfigureRedisActionインターフェースのBeanが実装されている場合は、RedisSessionConfiguraitonクラスに定義されたBeanは使われず、アプリケーション独自に定義したBeanが使われるようになります。

アプリケーション独自に定義したConfiguraRedisActionインターフェースのBeanが存在しない場合、RedisSessionPropertiesクラスのconfigreActionフィールドの値を元に、ConfigureNotifyKeyspaceEventsActionクラスかConfigureRedisAction.NO_OPクラスをBeanとして登録します。

RedisSessionPropertiesクラスのconfigureActionの値によって利用するConfigureRedisActionが変更されるため、 application.propertiesやapplication.ymlやJava System propertiesなどアプリケーション外から指定することができます。

spring.session.redis.configure-action: none # or notify_keyspace_events

spring.session.redis.configure-actionというプロパティ名に対してnoneを設定することでConfigureRedisAction.NO_OPクラスが利用され、 notify_keyspace_eventsを設定することでConfigureNotifyKeyspaceEventsActionクラスが利用されます。

This entry is released under version 2.0 of the Apache License.