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
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
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
jQueryをバージョンアップする前に使いたいjQuery Migrate
matsuo_atsushi
0
500
Lemonade + Foundry Toolkit でお手軽アプリ開発
seosoft
1
330
タクシーアプリ『GO』の バックエンド開発のおける AI利活用と若者のすべて
pyama86
3
2k
JavaDoc 再入門
nagise
1
350
生成AI時代にこそ効くGo | Why Go Works in the Age of Generative AI
mom0tomo
8
3.2k
Inside Stream API
skrb
1
720
気圧・高度・GPSを記録&可視化するアプリ「Koudo」を作った話
hjmkth
1
260
ローカルLLMを使ってB2Bサービスを作っていての学び
yaotti
0
170
IBM Bobを活用したレガシーアプリの最新化
oniak3ibm
PRO
1
200
Composerを使ったサプライチェーン攻撃の様子を眺めてみる #phpstudy
o0h
PRO
2
250
Developing with AI Agents — Codex, Claude Code & Cowork Practical Guide
x5gtrn
PRO
0
1.3k
Signal Forms: Details & Live Coding @enterJS 2026 in Mannheim
manfredsteyer
PRO
0
140
Featured
See All Featured
Imperfection Machines: The Place of Print at Facebook
scottboms
270
14k
コードの90%をAIが書く世界で何が待っているのか / What awaits us in a world where 90% of the code is written by AI
rkaga
62
44k
Why You Should Never Use an ORM
jnunemaker
PRO
61
9.9k
The Hidden Cost of Media on the Web [PixelPalooza 2025]
tammyeverts
2
330
Game over? The fight for quality and originality in the time of robots
wayneb77
1
200
Visualizing Your Data: Incorporating Mongo into Loggly Infrastructure
mongodb
49
10k
How STYLIGHT went responsive
nonsquared
100
6.2k
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
12
1.7k
Introduction to Domain-Driven Design and Collaborative software design
baasie
1
840
For a Future-Friendly Web
brad_frost
183
10k
Mobile First: as difficult as doing things right
swwweet
225
10k
Sam Torres - BigQuery for SEOs
techseoconnect
PRO
0
290
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 という選択肢もあるよ
ありがとうございました