当前位置:网站首页>Interview difficulties: difficulties in implementing distributed session, this is enough!
Interview difficulties: difficulties in implementing distributed session, this is enough!
2022-07-19 12:51:00 【Hollis Chuang】
source :blog.csdn.net/Gaowumao/
article/details/124309548
How to solve the distributed problem Session The problem? ?
One 、 Solution list
Two 、Java Code implementation to solve distributed problems Session

The usual projects are in an application system , And all the operations are on one
TomcatServer , It doesn't triggerSession shareThe problem of , So it won't affect our system , But when we deploy multiple microservices , Match again Nginx When load balancing , If you don't deal with distributed Session problem , When we access different functions in the system, there will be frequent user login operations
Graphical analysis of causes :


Premise : User login function and commodity order module in the figure 、 The spike buying module belongs to a separate micro service module When users want to successfully log in to the other two modules in the diagram , because Nginx Use the default load balancing policy ( polling ), At this time, the request will be distributed to the back-end application one by one in chronological order , That is to say, the user is Tomcat1 After login successfully on , The user's information is placed in Tomcat1 Of Session in , After a while , The user wants to perform the function operation of second kill activity , The request was again Nginx Distributed to Tomcat2, And then Tomcat2 Upper Session There is no user information in , So there is a situation that allows users to log in again , In distributed services , Different functional modules are bound to be divided into their own microservices , Suppose you need to log in again to access a function , The user experience is bound to decline significantly !
How to solve the distributed problem Session The problem? ?
One 、 Solution list
1. Session Copy
advantage :
No need to change the code , It just needs to be modified Tomcat To configure
shortcoming :
Session Synchronous transmission occupies intranet broadband
More than one Tomcat The synchronization performance degrades exponentially
Session Take up memory , Cannot effectively expand horizontally
2. Front end storage
advantage :
No server memory
shortcoming :
There are security risks
Data size affected cookie Limit
Occupy Internet broadband
3. Session viscous
advantage :
No need to change the code
The server can expand horizontally
shortcoming :
Add new machines , Will return Hash, Cause re login
After the app restarts , Need to login again
4. Back end centralized storage
advantage :
Security
Easy to expand horizontally
advantage :
Increase complexity
You need to change the code
Two 、Java Code implementation to solve distributed problems Session
1. SpringSession - Redis Solve distributed Session
Add dependency
<!--Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--commons-pools2 Object pool dependency -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!--spring session rely on -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>add to Redis To configure
## Redis To configure
spring:
redis:
Server address
host: localhost
port
port: 6379
database
database: 0
Timeout time
connect-timeout: 10000ms
lettuce:
pool:
maximum connection
max-active: 8
Maximum connection blocking wait time Default -1
max-wait: 10000ms
Maximum free time Default 8
max-idle: 200
Minimum free connection Default 8
min-idle: 5Business logic implementation
/**
* Login function
* @param loginVo
* @return
*/
@Override
public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
String username = loginVo.getUserName();
String password = loginVo.getPassword();
User user = userMapper.selectByUserName(username);
if (user == null){
throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
}
// Determine if the password is correct
if (!MDUtils.formPassToDBPass(password,user.getSalt()).equals(user.getPassword())){
throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
}
// Use UUID Generate a string instead of Cookie
String ticket = UUIDUtil.uuid();
request.getSession().setAttribute(ticket,user);
CookieUtil.setCookie(request,response,"userTicket",ticket);
return RespBean.success();
}View control layer
/**
* Jump to product list
* @param session
* @param model
* @return
*/
@RequestMapping("/toList")
public String toList(HttpSession session, Model model,@CookieValue("userTicket")String ticket){
if (StringUtils.isEmpty(ticket)){
return "login";
}
User user = (User) session.getAttribute(ticket);
if (user == null){
return "login";
}
model.addAttribute("user",user);
return "goodsList";
}Log on to the test

open Redis Management software discovery Session Information has been added to Redis It's in 
2. Redis Solve distributed Session
Import dependence
<!--Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--commons-pools2 Object pool dependency -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>Business logic layer
@Override
public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
String username = loginVo.getUserName();
String password = loginVo.getPassword();
User user = userMapper.selectByUserName(username);
if (user == null){
throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
}
// Determine if the password is correct
if (!MDUtils.formPassToDBPass(password,user.getSalt()).equals(user.getPassword())){
throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
}
// success Cookie
String ticket = UUIDUtil.uuid();
// Store user information in redis in
redisTemplate.opsForValue().set("userTicket",ticket);
redisTemplate.opsForValue().set("user:"+ticket,user);
//request.getSession().setAttribute(ticket,user);
CookieUtil.setCookie(request,response,"userTicket",ticket);
return RespBean.success();
}
/**
* according to cookie obtain cookie
* @param ticket
* @return
*/
@Override
public User getUserByByCookie(String ticket,HttpServletRequest request,HttpServletResponse response) {
if (StringUtils.isEmpty(ticket)){
return null;
}
User user = (User) redisTemplate.opsForValue().get("user:" + ticket);
if (user == null){
CookieUtil.setCookie(request,response,"userTicket",ticket);
}
return user;
}View control layer
/**
* Jump to product list
* @param session
* @param model
* @return
*/
@RequestMapping("/toList")
public String toList(HttpSession session, Model model,HttpServletRequest request,HttpServletResponse response){
String ticket = (String) redisTemplate.opsForValue().get("userTicket");
if (StringUtils.isEmpty(ticket)){
return "login";
}
//User user = (User) session.getAttribute(ticket);
User user = userService.getUserByByCookie(ticket, request, response);
if (user == null){
return "login";
}
model.addAttribute("user",user);
return "goodsList";
}Test success

see Redis Management tools

End
My new book 《 In depth understanding of Java The core technology 》 It's on the market , After listing, it has been ranked in Jingdong best seller list for several times , At present 6 In the discount , If you want to start, don't miss it ~ Long press the QR code to buy ~

Long press to scan code and enjoy 6 A discount
Previous recommendation
An online accident , I suddenly realized the essence of asynchrony
There is Tao without skill , It can be done with skill ; No way with skill , Stop at surgery
Welcome to pay attention Java Road official account

Good article , I was watching ️
边栏推荐
- Can you view MySQL data table structure in two ways?
- 招生宣传-江南大学
- Binary tree 2-symmetry recursion problem
- Dynamic memory planning
- 逻辑运算符1(阁瑞钛伦特软件-九耶实训)
- 虞美人·寄公度
- Committer identity unknown *** Please tell me who you are...
- 超声波传感器系列文章汇总
- Will webgpu become the killer of webgl?
- Opencv tutorial 03: how to track an object in a video
猜你喜欢
随机推荐
Acwing785. Quick sort
Do you still need to release the database connection manually with typeorm
数组去重 数组排序 最大值 求和 类数组转化 过滤数组
云犀&腾讯云达成战略合作,加速拓展全球直播市场
hcip第四天笔记
Three minutes to understand the primary key, foreign key, non empty, unique and default constraints in mysql, and how to create a table
2022 global developer salary exposure: China ranks 19th, with an average annual salary of $23790
动态内存规划
How to run SH script file
mysql中对于数据库的基本操作
mysql如何删除数据表,被关联的数据表如何删除呢
竞赛笔记:Numpy学习笔记
整理了一份通用的内存管理驱动代码
Opencv based on DLCO descriptor matching
Learning record: call TFTLCD
Redis logical cluster creation
Att & CK actual combat series - red team actual combat (-)
Investment logic in market "uncertainty" 2020-03-18
云犀聚焦店播解决方案,加速全球化布局
Deep learning parameter initialization (II) Kaiming initialization with code











