1、单体服务结构
单体服务不存在会话共享的问题?
2、分布式架构
两种方案来解决会话共享的问题:
1、nginx ip-hash方式
nginx.conf配置
upstream ngixServers{
server localhost:8081;
server localhost:8082;
ip_hash;
}
server {
listen 8888;
server_name localhost;
location / {
proxy_pass http://ngixServers;
}
}
即一个ip只会请求到一个服务器上去
2、spring-session +redis方式
maven配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.example</groupId>
<artifactId>miaoshaStu</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--spring-session-->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
</dependencies>
</project>
@RestController
public class SpringSessionController {
@GetMapping("query")
@ResponseBody
public String query(HttpServletRequest request) {
HttpSession session = request.getSession();
session.setAttribute("hello","123123123");
System.out.println("----------sessionId-----------"+session.getId());
return String.valueOf(session.getAttribute("hello"));
}
}
?application.yml:
#redis
server:
port: 8081
redis:
host: localhost
password:
timeout: PT30M
#spring-session
session:
store-type: redis
timeout: PT30M
nginx.config配置:
upstream ngixServers{
server localhost:8081;
server localhost:8082;
}
server {
listen 8888;
server_name localhost;
location / {
proxy_pass http://ngixServers;
}
}
?请求:http://localhost:8888/query
?
?主要是两点:spring-session会让两个服务的sessionId保持一致(自定义httpSession),然后把相关参数设置在redis中以sessionId进行绑定
3、微服务架构
后续补充.........?
|