分为以下几步
1 配置信息
2 添加注解
3启动项目
配置信息
1)添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
2)配置信息
#端口号 server.port=8280 #redis #节点 spring.redis.cluster.nodes=192.168.4.52:6379,192.168.4.53:6379,192.168.4.54:6379
添加注解
1)编写代码(两个springboot项目,我这里只写其中一个,除了端口号不一样,其余都一样。这个代码很简单,访问set设置名称,再访问另一个服务get,如果得到了这个名称,即session共享成功)
@RestController public class MesUtil {@RequestMapping("get")public String getSession(HttpServletRequest request){return (String) request.getSession().getAttribute("user"); }@RequestMapping("set/{name}")public String setSession(@PathVariable String name, HttpServletRequest request){request.getSession().setAttribute("user",name); return "ok"; } }
2)添加注解,启动类
@SpringBootApplication @EnableRedisHttpSession public class Tomcat1Application {public static void main(String[] args) {SpringApplication.run(Tomcat1Application.class, args); } }
启动项目
启动两个项目,然后访问localhost:8280/set/liqing 显示 ok
再访问localhost:8281/get 显示liqing
没问题,完全ojbk
附录
注解原理:官网上有,它有一个过滤器SessionRepositryFilter,SessionRepositryRequestWrapper会将httpsession包装用它自己的springsession来代替httpsession,如果有就创建放入redis中,没有就新建一个放入redis中