举例两种方式实现Session共享问题
方法一:Nginx通过负载均衡IP地址固定绑定,解决Session共享
1. 修改Nginx.conf文件
2. 编写一个servlet并启动两个tomcat模拟session共享失败状态
@WebServlet("/NginxSessionServlet") public class NginxSessionServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("当前请求端口号:"+req.getLocalPort()); String action=req.getParameter("action"); //像session中存放数据 if(action.equals("setSession")){ req.getSession().setAttribute("username","lisi"); }else if (action.equals("getSession")){ resp.getWriter().write((String)req.getSession().getAttribute("username")); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } }
3. 从nginx运行页面存数据
4. 控制台效果 当前走的时8080端口
5. 运行页面取数据
6. 控制台效果 还是走8080端口
7. 我们再走一遍取数据方法 控制台效果
方法二:Spring-session+Redis解决Session共享
1. 创建Controller编写存取数据的方法
@RestController public class SessionController { //存放session值 @RequestMapping("setSession") public String setSession(HttpServletRequest request){ request.getSession().setAttribute("username","zhangsan"); return "success"; } //获取session @RequestMapping("getSession") public String getSession(HttpServletRequest request){ return (String)request.getSession().getAttribute("username"); } }
2. 创建启动类
@SpringBootApplication public class SpringBootStart { public static void main(String[] args) { SpringApplication.run(SpringBootStart.class); } }
3. 编写Application.yml文件
server: port: 8080 #redis配置 spring: redis:
4. 启动两遍启动类分别是8080端口和8090端口
5. 启动运行本地Redis
6. 运行页面访问存放数据地址
6. 查看Redis
7. 访问获取数据地址
8. 现在更换端口号获取数据
server:
port: 8080
#redis配置
spring:
redis: