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
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
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
GKE アップグレード前に知っておきたい Blue/Green と PDB の関係
stkk
0
160
巨大モノリシックアプリ モダン化大作戦
ktcryomm
0
420
tsc.rip を支える技術 / Kyoto.なんか #8
susisu
0
4.4k
Swift愛好会100回記念 第1回を振り返る
jollyjoester
0
120
XHTMLが残したもの
yosuke_furukawa
PRO
2
640
フロントエンドUIフレームワークのこれまでとこれから
ssssota
4
2.1k
DroidKaigi 2026 「個人開発という実験場: Android エンジニアが手にする4つの自由」
slashnephy
0
230
App Intentsのビルドプロセスを支える技術
kntkymt
0
180
Claude Codeを組織的に動かして月400PRを実現した話
happy_ryo
0
260
スマート反転とウェブアクセシビリティ
camiha
0
180
AI Agent時代のリアーキテクチャ戦略と実践
hokaccha
6
3.4k
【高い買い物LT会】初任給で話題の国産フィジカルAIを買った話
akagami
PRO
0
130
Featured
See All Featured
The Curse of the Amulet
leimatthew05
2
14k
Test your architecture with Archunit
thirion
2
2.4k
jQuery: Nuts, Bolts and Bling
dougneiner
66
8.6k
SERP Conf. Vienna - Web Accessibility: Optimizing for Inclusivity and SEO
sarafernandez
2
1.6k
Skip the Path - Find Your Career Trail
mkilby
1
220
Chasing Engaging Ingredients in Design
codingconduct
0
300
30 Presentation Tips
portentint
PRO
1
390
SEO Brein meetup: CTRL+C is not how to scale international SEO
lindahogenes
1
2.9k
Git: the NoSQL Database
bkeepers
PRO
432
67k
The SEO identity crisis: Don't let AI make you average
varn
0
550
Embracing the Ebb and Flow
colly
88
5.2k
Build The Right Thing And Hit Your Dates
maggiecrowley
39
3.4k
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 という選択肢もあるよ
ありがとうございました