Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
セッションデータの管理にSpring Sessionを利用する
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Kazuhiro Seo
August 06, 2022
Programming
3.3k
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
セッションデータの管理にSpring Sessionを利用する
Kazuhiro Seo
August 06, 2022
More Decks by Kazuhiro Seo
See All by Kazuhiro Seo
GitHub ActionsとAWSをOIDC認証で連携する
kazuhiro1982
1
200
Gradleとちょっと仲良くなろう
kazuhiro1982
0
100
JavaとWebAssembly
kazuhiro1982
0
140
SpringBoot 3.0 のNative Imageを試してみた
kazuhiro1982
0
450
AWSのLake Formation Governed Tablesを触ってみた
kazuhiro1982
0
440
VS CodeとRemote Containerで開発環境もコード管理しよう
kazuhiro1982
1
750
SpringBootをコンテナで動かしてみる
kazuhiro1982
0
430
Serverless FrameworkでWebサイトの更新を検知して通知する
kazuhiro1982
0
520
Other Decks in Programming
See All in Programming
CSC307 Lecture 17
javiergs
PRO
0
320
Skillsは効率化、Agentsは"自分の拡張"——Builder時代のエージェント編成(CC Night 2026)
wemra
1
130
Lessons from Spec-Driven Development
simas
PRO
0
200
Developing with AI Agents — Codex, Claude Code & Cowork Practical Guide
x5gtrn
PRO
0
1.3k
スマートグラスで並列バイブコーディング
hyshu
0
140
Strategic Design in the Frontend: Moduliths & Micro Frontends @DDDEurope
manfredsteyer
PRO
0
100
OSもどきOS
arkw
0
570
Make SRE Operations Easier with Azure SRE Agent
kkamegawa
0
6.1k
The ROI of Quarkus for Spring Boot Applications
hollycummins
0
120
Claspは野良GASの夢をみるか
takter00
0
190
Webフレームワークの ベンチマークについて
yusukebe
0
170
net-httpのHTTP/2対応について
naruse
0
480
Featured
See All Featured
Public Speaking Without Barfing On Your Shoes - THAT 2023
reverentgeek
1
420
The Power of CSS Pseudo Elements
geoffreycrofte
82
6.3k
SEO in 2025: How to Prepare for the Future of Search
ipullrank
3
3.5k
30 Presentation Tips
portentint
PRO
1
320
Unlocking the hidden potential of vector embeddings in international SEO
frankvandijk
0
840
[SF Ruby Conf 2025] Rails X
palkan
2
1.1k
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
4.3k
Designing for humans not robots
tammielis
254
26k
My Coaching Mixtape
mlcsv
0
150
Google's AI Overviews - The New Search
badams
0
1k
Designing for Performance
lara
611
70k
Collaborative Software Design: How to facilitate domain modelling decisions
baasie
1
250
Transcript
セッションデータ管理に Spring Session を利用する
自己紹介 妹尾 一弘 サーバーサイドエンジニア Java Do スタッフ 興味分野 AWS/ 開発環境/Java
Spring Session セッションデータの管理を抽象化できるモジュール
Session とは サーバ側でユーザーを識別する仕組み SessionID でユーザーを識別 サーバ側でユーザーごとのデータを保持
SessionID 生成の流れ( ※イメージ)
SpringBoot での セッションデータ利用シーン
ログイン情報 ログイン時にユーザー情報をセッションに保存 アクセス時にセッションから取り出して参照 @Controller public class IndexController { @RequestMapping("/") public
String index(Authentication user, ModelAndView mav) { mav.addObject("username", user.getName()); return "index"; } }
FlashAttribute @RequestMapping(value="/submit", method = RequestMethod.POST) public String submit(RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("message", "保存しました"); return "redirect:/index"; } @RequestMapping("/index") public String index(Model model, ModelAndView mav) { String message = (String)model.getAttribute("message"); if (message != null) { mav.addObject("message", message); } return "index"; }
FlashAttribute
FlashAttribute
FlashAttribute
その他の利用例 SessionAttribute SessonScopeBean
セッションの保存場所
デフォルトではオンメモリで管理される 高速な読み書きが必要
高可用性構成の課題 異なるサーバにアクセスすると セッションデータを参照できない
対応方法 Sticky Session Session Repository の外部化
Sticky Session LoadBalancer の設定 同じセッションID のリクエストは同じインスタン スに転送する
Sticky Session の課題 サーバが再起動するとセッションデータが失われる インスタンス障害でフェイルオーバーしたときにも セッションデータが失われる スケールアウトしても負荷が下がりにくい
Session Repository の外部化
Spring Session Session Repository へのアクセスを抽象化する Configuration のみで保存先を切り替えられる アプリケーションコードは変更不要
利用開始 必要な依存関係を定義 // build.gradle dependencies { // SpringSession共通ライブラリ implementation 'org.springframework.session:spring-session-core
// Repositoryごとのライブラリ implementation 'org.springframework.session:spring-session-jdbc implementation 'org.springframework.boot:spring-boot-starter-jdb runtimeOnly 'mysql:mysql-connector-java' ...
実装されているRepository
Configuration 例 - JDBC - @Configuration @EnableJdbcHttpSession public class SessionConfig
{ @Bean public DataSource dataSource() { return DataSourceBuilder.create() .url("jdbc:mysql://session-db:3306/sessions") .username(userName) .password(password) .driverClassName("com.mysql.cj.jdbc.Driver") .build(); } }
Configuration 例 - Redis - @Configuration @EnableRedisHttpSession public class SessionConfig
{ @Bean public LettuceConnectionFactory redisConnectionFactory() { return new LettuceConnectionFactory(); } }
SessionFilter
実装されているRepository
Spring Session Hazelcast SpringBoot 組み込みで動かせる spring-session-data-*** はSpring Data 経由で 外部Repository
にアクセスする
Hazelcast インメモリデータグリッドを提供するOSS 分散コンピューティング環境をクラスタ化して データストアとして利用できる
Spring Session Hazelcast
Spring Session Hazelcast のメリット 外部データストアの構築・運用が不要 StickySession より可用性が高い
Spring Session Hazelcast のデメリット ライフサイクルがアプリケーションと同一になる アプリケーションがクラスターごとダウンしたり Blue/Green デプロイで一気に入れ替えると セッションが失われる
スケールアウト時の動き
スケールアウト時の動き
スケールアウト時の動き
Discovery Mechanism どうやってお互いを見つけてクラスタ化するか TCP/IP マルチキャスト Cloud Discovery
TCP/IP hazelcast: network: join: tcp-ip: enabled: true member-list: - 192.168.1.21
- 192.168.1.22
マルチキャスト hazelcast: network: join: multicast: enabled: true multicast-group: 224.2.2.3 multicast-port:
54327 multicast-time-to-live: 32 multicast-timeout-seconds: 2 trusted-interfaces: - 192.168.1.102
Cloud Discovery 各クラウドサービスのDiscovery Mechanism を 利用するプラグイン
AWS(ECS) の場合 依存関係の追加 dependencies { ... implementation 'com.hazelcast:hazelcast-aws:3.4' }
AWS ECS Java Configuration @Bean public Config hazelcastConfig() { var
config = new Config(); var networkConfig = config.getNetworkConfig(); networkConfig.getJoin().getMulticastConfig().setEnabled(false); networkConfig.getJoin().getAwsConfig().setEnabled(true); networkConfig.getInterfaces().setEnabled(true).addInterface("17 ... }
AWS ECS Task Role const springBootTaskRole = new iam.Role(this, 'SpringBoot
TaskRol assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'), roleName: 'springboot-task-role', inlinePolicies: { 'allow-discover-task-policy': new iam.PolicyDocument({ statements: [ new iam.PolicyStatement({ actions: [ 'ecs:ListTasks', 'ecs:DescribeTasks', 'ec2:DescribeNetworkInterfaces', ], resources: ['*'], })]})}})
AWS ECS Discovery Flow 1. メタデータから自身の属するECS クラスターを取得 2. ListTasks API
でタスク一覧を取得 3. DescribeTasks API でタスクのIP を特定 4. Hazelcast cluster に参加
Cloud Discovery Plugins AWS Azure GCP k8s etc…
まとめ 必要な可用性に応じたセッション管理をしよう Spring Session 便利 Hazelcast という選択肢もあるよ
ありがとうございました