↑こちらの去年の記事で、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.