nginx+tomcat+redis(session共享)實現負載均衡
阿新 • • 發佈:2019-01-24
- redis的session共享的包和nginx的windows版本下載地址
連結:http://download.csdn.net/download/u014464624/10103218
- 安裝windows版nginx,在虛擬機器上安裝兩臺tomcat伺服器,我採用不同的埠號區分兩臺tomcat伺服器
cmd視窗關閉nginx命令: nginx.exe -s stop
- 配置nginx.conf的配置檔案
worker_processes 1;#工作程序的個數,一般與計算機的cpu核數一致
events {
worker_connections 1024 ;#單個程序最大連線數(最大連線數=連線數*程序數)
}
http {
include mime.types; #副檔名與檔案型別對映表
default_type application/octet-stream;#預設檔案型別
sendfile on;#開啟高效檔案傳輸模式,sendfile指令指定nginx是否呼叫sendfile函式來輸出檔案,對於普通應用設為 on,如果用來進行下載等應用磁碟IO重負載應用,可設定為off,以平衡磁碟與網路I/O處理速度,降低系統的負載。注意:如果圖片顯示不正常把這個改成off。
keepalive_timeout 65; #長連線超時時間,單位是秒
gzip on;#啟用Gizp壓縮
#伺服器的叢集
upstream netitcast.com { #伺服器叢集名字,windows需要修改hosts檔案
server 192.168.1.159:18080 weight=1;#伺服器配置 weight是權重的意思,權重越大,分配的概率越大。
server 192.168.1.159:28080 weight=2;
}
#當前的Nginx的配置
server {
listen 80;#監聽80埠,可以改成其他埠
server_name localhost,netitcast.com;############## 當前服務的域名
location ~.*\.(jsp|action)$ {
proxy_pass http://netitcast.com;
proxy_redirect default;
}
location ~* .(html|jpg|jpeg|png|bmp|gif|ico|mp3|mid|wma|mp4|swf|flv|rar|zip|txt|doc|ppt|xls|pdf)$ {
root static;
expires 7d; #過期時間為7天
}
location ~* .(js|css)$ {
root static;
expires 6h; #過期時間為7天
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
- 在nginx的安裝目錄下配置靜態資源
構建路徑和專案釋出路徑保持一致,我的專案地址為http://ip:埠(域名)/data,我的js載入地址為
http://ip:埠(或者域名)/data/appzhongzhi/tymanager/config/js/query.js
將commons-pool2-2.3.jar,jedis-2.7.2.jar和tomcat-redis-session-1.0-SNAPSHOT.jar放到tomcat的lib資料夾下
配置tomcat的context.xml新增redis配置資訊
<Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
<Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
host="192.168.1.122"
port="6379"
database="1"
maxInactiveInterval="60" />
tomcat1的struts.jsp
<%
System.out.print("tomcat1的sessionId為:"+session.getId());
response.sendRedirect("config-browser/actionNames.action");
%>
tomcat2的struts.jsp
<%
System.out.print("tomcat2的sessionId為:"+session.getId());
response.sendRedirect("config-browser/actionNames.action");
%>
多重新整理幾次,第一次訪問的是tomcat2伺服器,隨後隨機訪問的tomcat1伺服器
他們的sessionId都是一樣的
- 載入圖片資源,兩個tomcat伺服器都不存在01.jpg,將圖片資源放到nginx\nginx-1.12.2\static\data\upload
tomat伺服器(注意是兩個,我這裡寫了一個)專案根路徑下放一個index1.jsp,程式碼內容如下:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>這是tomcat2的訪問頁面</title>
</head>
<body>
<center>
<p>this is tomcat2 example</p>
<p>sessionId為:<%=session.getId()%></p>
<img alt="這是個妹子" src="./upload/01.jpg">
</center>
</body>
</html>