初歩から学ぶSpring Session using Db2 第1回:基本動作

# 0. はじめに  

Spring Sessionお試し用Webアプリは[こちら]( http://github.com/kyosuke-yamagata/spring-session-with-db2-demo/tree/master )で公開しています。

# 1. 導入 〜 前回おさらい 〜 
[前回の記事](https://qiita.com/darjeeling/items/4b1eb9db444805f070f2)で、Spring Session利用環境が整いました。

今回は、基本動作を実機確認します。

# 2. Spring Session お試し用Webアプリ起動 
お試し用Webアプリをcodeダウンロード&buildして、
Dockerを導入したホスト上で実行します。

正常に起動すると以下。

```text:アプリ起動
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
:: Spring Boot ::               (v2.4.0)

INFO---[           main]c.e.s.session.db2.demo.DemoApplication  [Starting DemoApplication using Java 15 on user.local with PID 1828 ([workspace dir]demo/target/classes started by [user name] in [git dir]/repository/demo)
INFO---[           main]c.e.s.session.db2.demo.DemoApplication  [No active profile set, falling back to default profiles: default
INFO---[           main]o.s.b.w.embedded.tomcat.TomcatWebServer [Tomcat initialized with port(s): 8080 (http)
INFO---[           main]o.apache.catalina.core.StandardService  [Starting service [Tomcat]
INFO---[           main]org.apache.catalina.core.StandardEngine [Starting Servlet engine: [Apache Tomcat/9.0.39]
INFO---[           main]o.a.c.c.C.[Tomcat].[localhost].[/]      [Initializing Spring embedded WebApplicationContext
INFO---[           main]w.s.c.ServletWebServerApplicationContext[Root WebApplicationContext: initialization completed in 697 ms
INFO---[           main]com.zaxxer.hikari.HikariDataSource      [HikariPool-1 - Starting...
INFO---[           main]com.zaxxer.hikari.HikariDataSource      [HikariPool-1 - Start completed.
INFO---[           main]o.s.s.concurrent.ThreadPoolTaskExecutor [Initializing ExecutorService 'applicationTaskExecutor'
INFO---[           main]o.s.b.w.embedded.tomcat.TomcatWebServer [Tomcat started on port(s): 8080 (http) with context path ''
INFO---[           main]s.a.ScheduledAnnotationBeanPostProcessor[No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
INFO---[           main]c.e.s.session.db2.demo.DemoApplication  [Started DemoApplication in 1.643 seconds (JVM running for 7.199)
INFO---[nio-8080-exec-1]o.a.c.c.C.[Tomcat].[localhost].[/]      [Initializing Spring DispatcherServlet 'dispatcherServlet'
INFO---[nio-8080-exec-1]o.s.web.servlet.DispatcherServlet       [Initializing Servlet 'dispatcherServlet'
INFO---[nio-8080-exec-1]o.s.web.servlet.DispatcherServlet       [Completed initialization in 1 ms
```

# 3. 確認:セッション永続化
まずはコンテナに入って、Db2側テーブルに何もデータ無いこと確認。

```text:テーブル確認
[db2inst1@cb23f39d4164 ~]$ db2 "select * from db2inst1.SPRING_SESSION;"

PRIMARY_ID                           SESSION_ID                           CREATION_TIME        LAST_ACCESS_TIME     MAX_INACTIVE_INTERVAL EXPIRY_TIME          PRINCIPAL_NAME                                                                                      
------------------------------------ ------------------------------------ -------------------- -------------------- --------------------- -------------------- ----------------------------------------------------------------------------------------------------

  0 record(s) selected.
```

続いて下記URLに、Webブラウザでアクセス。
http://localhost:8080/sessionDemo
Webアプリの標準出力に、以下が出力されていれば正常稼働です。

```text:標準出力
HttpSession.setAttribute Called. Count:1
```

Webブラウザ側は以下。
![スクリーンショット 2020-12-09 0.09.43.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/32882/098850bb-cbd5-391d-2128-881b764394ff.png)

お試し用Webアプリ、該当Controllerは[こちら](https://github.com/kyosuke-yamagata/spring-session-with-db2-demo/blob/0e13ca71160d9c0a0d27e862d4fe88489156816c/demo/src/main/java/com/example/spring/session/db2/demo/HttpSessionUsingController.java#L16)。

挙動は以下です。

- Controller内のstaticなcounter変数を使い、HttpSessionにkey-valueを保持。

```java:HttpSessionUsingController.java
	private static int setAttr_count = 0;
```
- /sessionDemoにリクエスト有る毎にcounterを1加算。
- 裏側でSpring Sessionが働く。既にデータ有れば、セッション復元。
- 処理が完了し次第、Db2テーブルにセッション永続化。


```java:HttpSessionUsingController.java
	@GetMapping("/sessionDemo")
	public static String sessionDemo(HttpServletRequest req, HttpServletResponse resp) {
		HttpSession hs = req.getSession();
		hs.setAttribute("demoKey"+setAttr_count, "demoValue"+setAttr_count);
		setAttr_count++;

		String return_str = "HttpSession.setAttribute Called." + " Count:" + setAttr_count;
		System.out.println(return_str);
		
		return return_str;
	}
```

想定どおりに動いていれば、Db2コンテナ側のテーブルには
先ほどのアクセスを契機に生成されたセッションが、永続化されている筈です。

確認してみましょう。

```text:テーブル確認
[db2inst1@cb23f39d4164 ~]$ db2 "select * from db2inst1.SPRING_SESSION;"

PRIMARY_ID                           SESSION_ID                           CREATION_TIME        LAST_ACCESS_TIME     MAX_INACTIVE_INTERVAL EXPIRY_TIME          PRINCIPAL_NAME                                                                                      
------------------------------------ ------------------------------------ -------------------- -------------------- --------------------- -------------------- ----------------------------------------------------------------------------------------------------
484dc780-e9d0-4d17-bc75-71a025944b1e 462fae51-012d-432f-b80e-f27413c85555        1607347460733        1607347460974                  1800        1607349260974 -                                                                                                   

  1 record(s) selected.

[db2inst1@cb23f39d4164 ~]$
[db2inst1@cb23f39d4164 ~]$ db2 "select * from db2inst1.SPRING_SESSION_ATTRIBUTES;"

SESSION_PRIMARY_ID                   ATTRIBUTE_NAME                                                                                                                                                                                           ATTRIBUTE_BYTES                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
------------------------------------ -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
484dc780-e9d0-4d17-bc75-71a025944b1e demoKey0                                                                                                                                                                                                 x'ACED000574000A64656D6F56616C756530'                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              

  1 record(s) selected.

```

しっかり永続化されている、みたいですね。

# 4. 確認: セッション取得

データ永続化しても、使えなければ片手落ち。
永続化したセッションを取得できるか、確認しましょう。

下記URLにアクセスします。
http://localhost:8080/getAllInsertedValues

実装は[こちら](https://github.com/kyosuke-yamagata/spring-session-with-db2-demo/blob/0e13ca71160d9c0a0d27e862d4fe88489156816c/demo/src/main/java/com/example/spring/session/db2/demo/HttpSessionUsingController.java#L28)。

セッション情報に保持しているKeyおよび、対のValueが
Json形式で出力されます。

![スクリーンショット 2020-12-09 0.20.46.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/32882/f0e4adb7-d53b-8a10-a409-ec9b7be4ce70.png)

実装の観点では以下の通り
普段のWebアプリと変わらずに、HttpSession用いていることが特徴です。

```java:HttpSessionUsingController.java
	public static String getAllInsertedValue(HttpServletRequest req, HttpServletResponse resp) {
		HttpSession hs = req.getSession();
		// 割愛
	}
```

# 5. 確認: セッション取得 with webアプリ再起動

「本当に"永続化した"セッション情報が使えているか？」
「実はオンメモリで動いてないか？」観点で、シナリオ追加です。

さきほど利用したブラウザは閉じずに、置いておきつつ
お試し用Webアプリを停止＆起動してみます。
（スクショ割愛）

その後、再度Webブラウザで、下記URLにアクセス。
http://localhost:8080/getAllInsertedValues

Webアプリ停止する直前と
全く同一のKeyおよびValueが、画面に表示されていれば成功です。

![スクリーンショット 2020-12-09 0.30.57.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/32882/fe3def7e-a7ab-fe60-e49e-6d89b95bb8b6.png)
よしよし、大丈夫ですね。

# 6. 終わりに
第1回は、お試し用Webアプリの挙動をベースに
Spring Session基本動作を紹介させて頂きました。

今回は手動で、アプリ起動・停止しましたが
AWS Lambdaやkubernetesクラスタなど、クラウドネイティブに
稼働サーバが自動で休眠・再起・増台し得る環境において、有用な機能だと思います。

次回は、いつになるか不明ですが…
反響あれば、Spring Session発展編を扱う予定。乞うご期待です。