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
Kazuhiro Seo
August 06, 2022
Programming
3.7k
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
560
GitHub ActionsとAWSをOIDC認証で連携する
kazuhiro1982
1
240
Gradleとちょっと仲良くなろう
kazuhiro1982
0
130
JavaとWebAssembly
kazuhiro1982
0
170
SpringBoot 3.0 のNative Imageを試してみた
kazuhiro1982
0
460
AWSのLake Formation Governed Tablesを触ってみた
kazuhiro1982
0
470
VS CodeとRemote Containerで開発環境もコード管理しよう
kazuhiro1982
1
780
SpringBootをコンテナで動かしてみる
kazuhiro1982
0
440
Serverless FrameworkでWebサイトの更新を検知して通知する
kazuhiro1982
0
540
Other Decks in Programming
See All in Programming
mrbgem 三角測量 開発
ogom
0
170
GemmaをJevのように使ってみる / Use Gemma like Jev
kishida
5
460
AGENTS.md Is Not Enough:Build Skills, Don't Download Them
lx_t
0
130
WebRTC映像をAirPlayに対応させる挑戦.pdf
monolithic_adam
0
330
設計次第でAIコードの読む量は減らせる / designing-for-code-reading
minodriven
32
14k
iOS 27でニュースアプリはどう変わる!? 〜日経電子版の新機能対応と、開発事例から〜
lynnswap
7
13k
Apple Intelligence を用いた個人情報誤送信防止、及びユーザーリクエスト体験の改善について
yukiny
0
270
ソニーのクラウド共通基盤の変遷とAI時代の開発スタイルに合わせた進化 / The Journey of Sony’s Common Cloud Platform and Its Evolution for AI-Native Development
kenjiyoneyama
0
200
Augmenting AI with the Power of Jakarta EE
ivargrimstad
0
450
速く作れる。その次は、速く確かめられる開発へ 〜AIネイティブ開発を支える、Shift Down〜 / Can build fast. Next, moving to development where we can verify fast.
rkaga
8
5.3k
AI が書く Go コードの品質を劇的に向上させる Linter: “declscope”
mpyw
0
460
Findy - エンジニア向け会社紹介/Findy Company Deck
findyinc
6
400k
Featured
See All Featured
Embracing the Ebb and Flow
colly
88
5.2k
16th Malabo Montpellier Forum Presentation
akademiya2063
PRO
0
390
SEOcharity - Dark patterns in SEO and UX: How to avoid them and build a more ethical web
sarafernandez
0
290
Building a A Zero-Code AI SEO Workflow
portentint
PRO
0
750
Why Your Marketing Sucks and What You Can Do About It - Sophie Logan
marketingsoph
0
420
Testing 201, or: Great Expectations
jmmastey
46
8.3k
The B2B funnel & how to create a winning content strategy
katarinadahlin
PRO
1
550
The Cult of Friendly URLs
andyhume
79
7k
Amusing Abliteration
ianozsvald
1
320
YesSQL, Process and Tooling at Scale
rocio
174
15k
Principles of Awesome APIs and How to Build Them.
keavy
128
18k
Bash Introduction
62gerente
615
220k
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 という選択肢もあるよ
ありがとうございました