這篇文章主要介紹了Nginx Session共享問題解決方案解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
Nginx解決Session共享問題:
1.nginx或者h(yuǎn)aproxy做的負(fù)載均衡,用nginx做的負(fù)載均衡可以添加ip_hash這個配置;用haproxy做的負(fù)載均衡可以用balance source這個配置,從而使用一個IP的請求發(fā)到同一個服務(wù)器;
2.利用數(shù)據(jù)庫同步session;
3.利用cookie同步session數(shù)據(jù),但是安全性差,http請求都需要帶參增加了帶寬消耗;
4.Tomcat配置session共享;
5利用session集群存放Redis;
1:創(chuàng)建一個工程,啟動兩個Tomcat
2:編寫一個servlet測試
package com.zn.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/nginxSessionServlet")
public class SessionIPServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("當(dāng)前請求端口:"+request.getLocalPort());
String action=request.getParameter("action");
//向Session中存放一個數(shù)據(jù)
if(action.equals("setSession")){
request.getSession().setAttribute("username","zhangsan");
}else if(action.equals("getSession")){
response.getWriter().write((String)request.getSession().getAttribute("username"));
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
3、沒有Nginx的訪問效果展示
分別訪問8080和8081
4.配置nginx.conf文件
upstream myserver{
ip_hash;
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
server{
listen 81;
server_name www.bproject.com;
location / {
root html;
proxy_pass http://myserver;
index index.html index.htm;
}
}
5.再次訪問
方法二、利用spring-session+Redis實(shí)現(xiàn)session共享
1:導(dǎo)入依賴
<!--spring boot 與redis應(yīng)用基本環(huán)境配置 -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<!--spring session 與redis應(yīng)用基本環(huán)境配置,需要開啟redis后才可以使用,不然啟動Spring boot會報錯 -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
2:創(chuàng)建controller測試
@RestController
public class SessionController {
@RequestMapping("/setSession")
public String setSession(HttpServletResponse response, HttpServletRequest request) throws IOException {
request.getSession().setAttribute("username","wang");
return "success";
}
@RequestMapping("/getSession")
public String getSession(HttpServletRequest request,HttpServletResponse response){
String username = (String) request.getSession().getAttribute("username");
return username;
}
}
3:application.properties文件
server.port=8082
#server.port=8083
#redis配置
spring.redis.password: wang2003
4:啟動項目測試
結(jié)論:該方案配置簡單,數(shù)據(jù)安全且穩(wěn)定,效率高,被普遍使用;
注意:在Redis中刪除這個數(shù)據(jù)包,8082和8083端口都get不到session了,說明了session沒有存在在JVM中,而是轉(zhuǎn)存在Redis中;
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。