LoginSignup
1
2

Spring Boot 3.x への移行で、セッション周りではまったこと

Posted at

Spring Boot 3.x への移行で、セッション周りではまったこと

たいした話ではないのでのすが、Spring Boot 2.x -> 3.x での移行で、セッション周りではまったことの備忘録です。

Spring Boot 3.x での変更点

以下にマイグレガイドがあります。

Spring Boot 3.0 Migration Guide · spring-projects/spring-boot Wiki

それによると、spring.session.store-type による明示的な構成はサポートされなくなりました。複数のセッションストアの実装がクラスパス上にある場合は、固定順で使用する実装が選択されるようです。

優先順位は、Web に記述されていますが、

  1. Redis
  2. JDBC
  3. Hazlecast
  4. MongoDB

となっています。

それ以外には、@EnableRedisHttpSession などのアノテーションを明示的に指定する方法があります。

今回 Sprint Boot 2.x の構成には、以下があったので 安直に @EnableRedisHttpSession を指定しました。

spring.session.store-type=redis

外部からの構成変更が効かない

通常はセッションの有効期間は1800秒がデフォルト値ですが、この値を変更したいと思い、spring.session.timeout を設定しましたがどうも効いてないようです。 他にも server.servlet.session.timeout なども試しましたうまくいきません。

@EnableRedisHttpSession を指定しつつ、application.yml に以下の設定を行います。

spring:
  session:
    timeout: 180s

セッションの有効時間を取得するコードを書いてみます。

    @GetMapping("/s1")
    public Map<String, Object> s1(HttpSession session) {
        session.setAttribute("test", "value");
        return Map.of(
            "id", session.getId(),
            "date", (new Date()).toString(),
            "maxInactiveInterval", session.getMaxInactiveInterval());
    }

curl でアクセスしてみますが、常に 1800 を返します。

$ curl -s http://localhost:8080/s1 | jq
{
  "date": "Wed Oct 04 11:41:29 JST 2023",
  "id": "e543ea6d-8141-4ad3-8c6f-15bbae3cc7ad",
  "maxInactiveInterval": 1800
}

@EnableRedisHttpSession を外してみますと、spring.session.timeout が効くようになりました。

curl -s http://localhost:8080/s1 | jq
{
  "date": "Wed Oct 04 11:43:44 JST 2023",
  "id": "a14b4f19-e196-4798-a75b-c35a609be146",
  "maxInactiveInterval": 180

クラスパスには Redis の実装しか通ってないので、明示的にアノテーションを指定しようがしまいが同じ振る舞いなのですが、明示的にアノテーションを指定すると spring.session.timeout が効かないようです。

@EnableRedisHttpSession を指定したい場合は、アノテーションにパラメーターを指定する必要があります。(ここで値を可変にする方法が分からなかったので、固定値にしていますが)

@SpringBootApplication
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 360)
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}

curl でアクセスしてみますと、360 が返ってきました。

curl -s http://localhost:8080/s1 | jq
{
  "maxInactiveInterval": 360,
  "id": "7c336543-51a7-4d2c-b2cd-4da747fa4986",
  "date": "Wed Oct 04 11:50:17 JST 2023"
}

まとめ

あとからググってみると、昔からわりとよくある話のようです。以下のような記事がありました。

同じ挙動なのに、アノテーション付けると効かないのは、ちょっと分かりづらいですね。

以上

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2