SpringBoot2 使用Spring Session集群
有几种办法:
1.扩展指定server
利用Servlet容器提供的插件功能,自定义HttpSession的创建和管理策略,并通过配置的方式替换掉默认的策略。缺点:耦合Tomcat/Jetty等Servlet容器,不能随意更换容器。
2.利用Filter
利用HttpServletRequestWrapper,实现自己的 getSession()方法,接管创建和管理Session数据的工作。spring-session就是通过这样的思路实现的。
3 利用spring session
Spring Boot中spring session支持方式:
JDBC、MongoDB、Redis、Hazelcast、HashMap
一、引入maven依赖
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
二、配置application.properties
server.port=8080 spring.redis.host=localhost spring.redis.port=6379 # spring session使用存储类型 spring.session.store-type=redis
- spirngboot默认就是使用redis方式,如果不想用可以填none。、
三、在启动类中加入@EnableRedisHttpSession 注解
package com.shyroke; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @EnableCaching @EnableRedisHttpSession @SpringBootApplication public class SpringbootSessionApplication { public static void main(String[] args) { SpringApplication.run(SpringbootSessionApplication.class, args); } }
四、编写控制器
package com.shyroke.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(value = "/") public class IndexController { @ResponseBody @RequestMapping(value = "/session") public Map<String, Object> getSession(HttpServletRequest request) { request.getSession().setAttribute("username", "admin"); Map<String, Object> map = new HashMap<String, Object>(); map.put("sessionId", request.getSession().getId()); return map; } @ResponseBody @RequestMapping(value = "/get") public String get(HttpServletRequest request) { String userName = (String) request.getSession().getAttribute("username"); return userName; } }
五、测试
- 先输入http://localhost:8080/session,在session中设置一个值
- http://localhost:8080/get,获取session中的值
- 复制这个工程,application.properties中的server.port=8081,然后访问“http://localhost:8081/get”,如下获取到了另一个工程中设置的session的值。
源码面前,了无秘密