SpingSession+redis解决分布式服务session共享问题

纵然是瞬间 提交于 2019-12-02 02:41:27

首先呢,先在windows环境搞个redis吧,下载地址:http://redis.cn/download.html

启动命令:cmd   redis-server.exe redis.windows.conf

停止命令,先启动客户端redis-cli.exe   再输入shutdown

添加密码:修改redis.windows.conf  搜索requirepass  

密码认证 在客户端输入auth 密码

以服务方式启动redis ,先查看windwos是否已经存在redis服务,如果存在 则执行 redis-server.exe --service-uninstall

如果不存在,则执行 redis-server.exe --service-install redis.windows.conf

然后手动启动redis服务

 

接下来编写springboot代码

xml如下:

<dependencies>
<!-- 必须引入,否则报错 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<!-- 热部署插件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

application.properties 如下

 

 

Controller类如下:

 

@RestController
public class HelloController {

@Value("${server.port}")
Integer port;

@GetMapping("set")
public String set(HttpSession session) {
session.setAttribute("user", port);
return String.valueOf(port);
}

@GetMapping("get")
public String get(HttpSession session) {
Integer port = (Integer) session.getAttribute("user");
return "port:" + port;
}
}

config配置类如下,忽略get和set请求的安全认证

@Configuration //配置类
@EnableWebSecurity // 注解开启Spring Security的功能
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) {
super.configure(web);
web.ignoring().antMatchers("/get").antMatchers("/set");
}
}

 

将项目打成jar包,使用maven install 或者到pom.xml路径下,执行mvn package命令,会将打好的jar包放入target目录下

 

使用jar包启动不同端口的两个项目

java -jar xxxx.jar --server.port=8081

java -jar xxx.jar --server.port=8082

 

访问http://localhost:8081/study/set   将端口放入session, 在访问http://localhost:8082/study/get 取出session ,可以看到取出的端口是一样的,session实现共享.

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!