Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
セッションデータの管理にSpring Sessionを利用する
Search
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
Kazuhiro Seo
August 06, 2022
Programming
3.6k
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
PostgreSQL 18で考えるUUID主キー
kazuhiro1982
0
530
GitHub ActionsとAWSをOIDC認証で連携する
kazuhiro1982
1
230
Gradleとちょっと仲良くなろう
kazuhiro1982
0
130
JavaとWebAssembly
kazuhiro1982
0
160
SpringBoot 3.0 のNative Imageを試してみた
kazuhiro1982
0
460
AWSのLake Formation Governed Tablesを触ってみた
kazuhiro1982
0
460
VS CodeとRemote Containerで開発環境もコード管理しよう
kazuhiro1982
1
770
SpringBootをコンテナで動かしてみる
kazuhiro1982
0
440
Serverless FrameworkでWebサイトの更新を検知して通知する
kazuhiro1982
0
540
Other Decks in Programming
See All in Programming
『寄り添うラジオ』をAIで作る 体験価値から逆算した、会話しないUXと品質設計
theoriatec2024
3
140
iOS開発×AI駆動開発 〜最近使って便利だったスキルの話〜
nogu66
0
140
What We Talk About When We Talk About XP
m_seki
2
450
業務時間外もAIに働いてもらう話
colorful12
3
10k
XP祭りでしか伝わらないフリップネタ #xpjug
murabayashi
0
120
AI Agent時代のリアーキテクチャ戦略と実践
hokaccha
6
3.5k
AIは賢い。でも実行環境は? CLIおじさんがAI時代に伝えたいこと ~ CLIおじさんがAI時代に伝えたいこと ~
curekoshimizu
1
220
{ Android | Kotlin } Gradle Plugin in 2026
ryunen344
1
300
Swift愛好会と私(ウホーイ) / Swift Fan Club and Uhooi
uhooi
0
150
まだ間に合う!今年の夏こそSchemeのマクロ展開器を完全理解!
omasanori
0
650
自分的「カンファレンスの楽しみ方」
syumai
0
200
Foundry Localでエージェント開発
seosoft
0
160
Featured
See All Featured
Dealing with People You Can't Stand - Big Design 2015
cassininazir
367
27k
Taking LLMs out of the black box: A practical guide to human-in-the-loop distillation
inesmontani
PRO
3
2.4k
Test your architecture with Archunit
thirion
2
2.4k
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
38
3k
End of SEO as We Know It (SMX Advanced Version)
ipullrank
3
4.4k
Lightning Talk: Beautiful Slides for Beginners
inesmontani
PRO
2
680
Why You Should Never Use an ORM
jnunemaker
PRO
61
10k
Kristin Tynski - Automating Marketing Tasks With AI
techseoconnect
PRO
0
510
The Web Performance Landscape in 2024 [PerfNow 2024]
tammyeverts
12
1.3k
Testing 201, or: Great Expectations
jmmastey
46
8.3k
Build your cross-platform service in a week with App Engine
jlugia
234
19k
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
194
17k
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 という選択肢もあるよ
ありがとうございました