# 檢查和安裝依賴項(gcc、正則表達式工具、傳送內容壓縮的zlib庫、openssl開啓https支持),-y表示靜默安裝
yum -y install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel
# 下載源碼包
wget http://nginx.org/download/nginx-1.10.2.tar.gz
# 解壓源碼包
tar zxvf nginx-1.10.2.tar.gz
# 進入解壓的目錄配置相關參數(可使用--help查看可選項)
cd nginx-1.10.2.tar.gz
/
./configure --help
./configure --user=www --group=www --prefix=/usr/local/webserver/nginx --with-http_stub_status_module --with-openssl=/data/soft/openssl-1.0.2j --with-http_ssl_module --with-http_realip_module --with-http_flv_module
Nginx編譯參數
--user 指定啓動程序所屬用戶
--group 指定組
--prefix 指定安裝路徑
--with-http_stub_status_module 安裝能夠監控nginx狀態的模塊
--with-http_ssl_module 啓用SSL支持javascript
# 安裝
make && make install
# 啓動nginx
ps -aux|grep nginx # 查看進程(正常工做的時候有守護進程和工做進程)
./nginx -h # 查看幫助
#! /bin/bash # # nginx - this script starts and stops the nginx daemon # # chkconfig: - 85 15 # description: Nginx is an HTTP(S) server, HTTP(S) reverse \ # proxy and IMAP/POP3 proxy server # # processname: nginx # config: /etc/nginx/nginx.conf # pidfile: /var/run/nginx/nginx.pid # Source function library. . /etc/rc.d/init.d/functions # Source networking configuration. . /etc/sysconfig/network # Check that networking is up. [ "$NETWORKING" = "no" ] && exit 0 nginx="/usr/local/webserver/nginx/sbin/nginx" prog=$(basename $nginx) NGINX_CONF_FILE="/usr/local/webserver/nginx/conf/nginx.conf" [ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx lockfile=/var/lock/nginx.lock start() { [ -x $nginx ] || exit 5 [ -f $NGINX_CONF_FILE ] || exit 6 echo -n $"Starting $prog: " daemon $nginx -c $NGINX_CONF_FILE retval=$? echo [ $retval -eq 0 ] && touch $lockfile return $retval } stop() { echo -n $"Stopping $prog: " killproc $prog -QUIT retval=$? echo [ $retval -eq 0 ] && rm -f $lockfile return $retval } restart() { configtest || return $? stop sleep 1 start } reload() { configtest || return $? echo -n $"Reloading $prog: " killproc $nginx -HUP RETVAL=$? echo } force_reload() { restart } configtest() { $nginx -t -c $NGINX_CONF_FILE } rh_status() { status $prog } rh_status_q() { rh_status >/dev/null 2>&1 } case "$1" in start) rh_status_q && exit 0 $1 ;; stop) rh_status_q || exit 0 $1 ;; restart|configtest) $1 ;; reload) rh_status_q || exit 7 $1 ;; force-reload) force_reload ;; status) rh_status ;; condrestart|try-restart) rh_status_q || exit 0 ;; *) echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}" exit 2 esac
將上面的shell腳本內容以Unix格式
(不能用dos哦)保存並命名爲nginx
,而後上傳到centos系統的/etc/init.d/
目錄,接着添加可執行權限,最後執行添加到開機啓動的命令:chkconfig --add nginx
、chkconfig nginx on
便可。css
最後,咱們可使用以下命令對Nginx服務進行操做:html
######啓動Nginx服務 [root@typecodes ~]# service nginx start ######中止Nginx服務 [root@typecodes ~]# service nginx stop ######重啓Nginx服務 [root@typecodes ~]# service nginx restart ######Nginx服務的狀態 [root@typecodes ~]# service nginx status ######在Nginx服務啓動的狀態下,從新加載nginx.conf這個配置文件 [root@typecodes ~]# service nginx reload
nginx的配置前端
nginx的主配置文件位於安裝目錄下的conf/nginx.conf
.java
user www www; worker_processes 8; #開啓全局錯誤日誌類型 error_log /data/logs/nginx/error.log info; #error_log logs/error.log notice; #error_log logs/error.log info; pid /data/logs/nginx/nginx.pid; #一個Nginx進程打開的最多文件描述數目 建議與ulimit -n一致 #若是面對高併發時 注意修改該值 ulimit -n 還有部分系統參數 而並不是這個單獨肯定 worker_rlimit_nofile 65535; events { #使用epoll模型提升性能 use epoll; #單個進程最大鏈接數 worker_connections 65535; } http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; tcp_nopush on; tcp_nodelay on; types_hash_max_size 2048; proxy_redirect off; proxy_set_header Host $host:$server_port; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 65; proxy_send_timeout 65; proxy_read_timeout 65; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; #日誌 access_log /data/logs/nginx/access.log; error_log /data/logs/nginx/error.log; #gzip 壓縮傳輸 gzip on; gzip_min_length 1k; #最小1K gzip_buffers 16 64K; gzip_http_version 1.1; gzip_comp_level 6; gzip_types text/plain application/x-javascript text/css application/xml application/javascript; gzip_vary on; upstream tomcat.dynamic { server 127.0.0.1:8000 fail_timeout=0; } upstream tomcat.static{ server 127.0.0.1:8080 fail_timeout=0; } server{ listen 8080; server_name static; location / { } location ~ .*\.(js|css|ico|png|jpg|eot|svg|ttf|woff) { #全部靜態文件直接讀取硬盤 root /data/soft/apache-tomcat-7.0.73/webapps/ROOT ; expires 30d; #緩存30天 } } # HTTPS server server { listen 4443 ssl; server_name dps.vivo.xyz; root /data/htdocs; index index.html index.htm ssl on; ssl_certificate server.pem; ssl_certificate_key server.key; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #啓用TLS1.一、TLS1.2要求OpenSSL1.0.1及以上版本,若您的OpenSSL版本低於要求,請使用 ssl_protocols TLSv1; ssl_ciphers HIGH:!RC4:!MD5:!aNULL:!eNULL:!NULL:!DH:!EDH:!EXP:+MEDIUM; ssl_prefer_server_ciphers on; #讓http請求重定向到https請求 error_page 497 https://$host:$server_port$request_uri; location / { } location ~ .*\.(js|css|ico|png|jpg|eot|svg|ttf|woff) { proxy_pass http://tomcat.static$request_uri; expires 30d; } location ~ .*$ { proxy_pass http://tomcat.dynamic$request_uri; } }
安裝Jdk和tomcat步驟省略,啓用tomcat的apr步驟請參考:https://my.oschina.net/u/1160316/blog/806956node
安裝完後,配置環境變量:mysql
vim /etc/profile,增長行linux
JAVA_HOME="/usr/local/webserver/jdk1.7.0_79" PATH="$JAVA_HOME/bin:$JAVA_HOME/jre/bin:/usr/local/webserver/mysql/bin:$PATH" CLASSPATH=.:$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar CATALINA_HOME=/data/soft/apache-tomcat-7.0.73 LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/webserver/apr/lib:/usr/local/apr/lib export JAVA_HOME PATH CLASSPATH LD_LIBRARY_PATH
實時獲取服務器的狀態:tail -f /opt/apache-tomcat-8.0.26/logs/catalina.out
nginx
配置tomcat開機自啓動git
編輯/etc/rc.d/rc.local
追加:
/data/soft/apache-tomcat-7.0.73/bin/startup.sh
tomcat的優化實際上就是合理配置$CATALINA_HOME/bin/catalina.sh
和$CATALINA_HOME/conf/server.xml
。
# windows下設置方法
#set JAVA_OPTS=%JAVA_OPTS% -server -Xms512m -Xmx512m -XX:PermSize=512M -XX:MaxPermSize=512m
# 經過內存設置充分利用服務器內存
# -server模式啓動應用慢,但能夠極大程度提升運行性能
# java8開始,PermSize被MetaspaceSize代替,MetaspaceSize共享heap,不會再有java.lang.OutOfMemoryError: PermGen space,能夠不設置
# headless=true適用於linux系統,與圖形操做有關,如生成驗證碼,含義是當前使用的是無顯示器的服務器,應用中若是獲取系統顯示有關參數會拋異常
# 可經過jmap -heap proccess_id查看設置是否成功
JAVA_OPTS=" -server -Xms2048m -Xmx2048m -XX:PermSize=256m -XX:MaxPermSize=512m -Djava.awt.headless=true"
vim /data/soft/apache-tomcat-7.0.73/conf/server.xml
<Connector port="8000" protocol="org.apache.coyote.http11.Http11AprProtocol" connectionTimeout="20000" redirectPort="443" proxyPort="443" URIEncoding="UTF-8" acceptCount="500" enableLookups="false" maxThreads="400" executor="tomcatThreadPool" /> <Executor name="tomcatThreadPool" namePrefix="req-exec-" maxThreads="1000" minSpareThreads="50" maxIdleTime="60000" /> <Valve className="org.apache.catalina.valves.RemoteIpValve" remoteIpHeader="x-forwarded-for" protocolHeader="x-forwarded-proto" protocolHeaderHttpsValue="https" httpsServerPort="4443"
源碼地址
nginx是一個反向代理服務器,它的負載均衡也是基於反向代理來實現的,反向代理的原理圖以下:
從瀏覽器角度來看,它並不知道tomcat的存在。
配置nginx將全部請求轉交給tomcat
編輯nginx.conf
,修改location
以下:
從新加載nginx:./nginx -s reload
。若是咱們的服務器IP地址是http://192.168.132.144/
,咱們提交的http://192.168.132.144/test.jsp
請求將被替換爲http://192.168.132.144:8080/test.jsp
.
所謂的負載均衡就是後臺有多個應用服務器tomcat
(集羣),nginx根據必定的策略(默認是平均策略)將請求轉發給多個tomcat分擔了來自前端的請求——最終多個後臺服務器均衡分擔了前端的負載。
在http節點中添加tomcat集羣:
# tomcat集羣
upstream tomcats{
server 127.0.0.1:8080;
server 192.168.132.145:8080;
server 192.168.132.146:8080;
}
配置location爲tomcat集羣
location / {
# root html;
index index.html index.htm;
# 將請求轉交給tomcat集羣
proxy_pass http://tomcats;
}
nginx的集羣配置詳解:
# upstream 配置一組後端服務器,
# 請求轉發到upstream後,nginx按策略將請求指派出某一服務器
# 即配置用於負載均衡的服務器羣信息
upstream backends {
#均衡策略
#none 輪詢(權重由weight決定)
#ip_hash
#fair
#url_hash
server 192.168.1.62:8080;
server 192.168.1.63;
# weight:權重,值越高負載越大;
# server 192.168.1.64 weight=5;
# backup:備份機,只有非備份機都掛掉了才啓用;
server 192.168.1.64 backup;
# down: 停機標誌,不會被訪問,主要用於停機維護
server 192.168.1.65 down;
# max_fails:達到指定次數認爲服務器掛掉;
# fail_timeout:掛掉以後過多久再去測試是否已恢復
server 192.168.1.66 max_fails=2 fail_timeout=60s;
}
例若有如下的配置:
server 192.168.61.22 weight = 6; # 60% 請求
server 192.168.61.23 weight = 4; # 40% 請求
ip_hash
根據客戶端的IP進行hash運算,產生的效果是若是用戶的IP不變每次訪問的都是同一臺後臺服務器。
配置只須要在upstream中加入ip_hash;
便可.
第三方策略
下面以fair模塊爲例,演示第三方策略的配置:
# 解壓
unzip nginx-upstream-fair-master.zip
# 編譯nginx的時候指定添加的第三方模塊
./configure --prefix=/opt/nginx --add-module=/root/nginx-upstream-fair-master
# 若是是首次安裝須要make && make install,已經安裝nginx只須要make便可,編譯結果在當前目錄的objs目錄下
make
# 使用objs/nginx 替換原來的nginx
/opt/nginx/sbin/nginx -s stop
cp nginx /opt/nginx/sbin/nginx
session其實是tomcat上的一個內存空間,因此在分佈式集羣的時候session存在一個問題。因爲nginx的轉發同一個用戶的請求可能被轉發到不一樣的Tomcat。
處理方式有如下3種:
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
<!-- 基於網絡廣播的策略,一個節點session變化,其它節點同步複製,節點多或數據量大時性能低下 -->
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster">
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<!--
1.tomcat集羣的端口衝突問題。例如同一臺服務器運行多個tomcat。
2.服務器通常有多塊網卡(內網和外網),tomcat都應該使用內網網卡
-->
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
address="auto"
port="4000" />
</Channel>
</Cluster>
2.修改應用的部署描述符web.xml告訴tomcat該應用支持分佈式。在web-app標籤下新增<distributable/>
.
下面介紹使用memcached來管理分佈式緩存。
memchched的安裝依賴於libevent.
## 安裝libevent
# 下載libevent
wget https://sourceforge.net/projects/levent/files/libevent/libevent-2.0/libevent-2.0.22-stable.tar.gz
# 解壓
tar zxvf libevent-2.0.22-stable.tar.gz
cd libevent-2.0.22-stable/
# configure
./configure -prefix=/opt/libevent
# 編譯和編譯安裝
make && make install
## 安裝memcached
wget http://www.memcached.org/files/memcached-1.4.24.tar.gz
tar axvf memcached-1.4.24.tar.gz
cd memcached-1.4.24/
./configure --prefix=/opt/memcached --with-libevent=/opt/libevent
make && make install
## 啓動分佈式緩存(後臺進程,以root用戶,監聽11211端口,使用內存128M,最大支持1024鏈接)
cd /opt/memcached/bin
./memcached -d -u root -p 11211 -m 128 -c 1024
全部的memcached服務器是同步的。
使用memcached管理session的工做原理(粘性session):
以tomcat爲主存儲,將session的變動存儲到memcached中,一旦1tomcat down,就從memcached2中取出session推送到tomcat2.
使用memcached管理session的工做原理(非粘性session):
tomcat自己並不存儲session,每次從共享的memcached中讀寫。
配置memcached:
複製jar包到tomcat/lib目錄,jar分三類
1)spymemcached.jar memcached java客戶端
2)msm相關的包
memcached-session-manager-{version}.jar 核心包
memcached-session-manager-tc{tomcat-version}-{version}.jar Tomcat版本相關的包
3)序列化工具包,有多種可選方案,不設置時使用jdk自帶序列化,其它可選kryo,javolution,xstream,flexjson等
msm-{tools}-serializer-{version}.jar
其它序列化工具相關包 通常第三方序列化工具不須要實現serializable接口配置Context,加入處理session的Manager MemcachedBackupSessionManager Context配置查找順序: 1)conf/context.xml 全局配置,做用於全部應用
2) conf/[enginename]/[hostname]/context.xml.default 全局配置,做用於指定host下所有應用
3) conf/[enginename]/[hostname]/[contextpath].xml 只做用於contextpath指定的應用
4) 應用META-INF/context.xml 只做用於本應用
5) conf/server.xml 下 做用於Context docBase指定的應用 因此,只但願session管理做用於特定應用,最好用3,4方式設置,但願做用全體,可用1,2,5設置。
Context.xml
的配置以下:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<!-- sticky session 最小配置-->
<!-- className 管理器類名 -->
<!-- memcachedNodes memcached服務器節點,以節點名:主機:端口形式表示,其中節點名隨意命名,但不一樣tomcat間要一致 -->
<!-- sticky隱含默認值爲true,此時爲sticky session模式 -->
<!-- failoverNodes 僅適用於sticky模式, n1表示主要將session備份到n2,若是n2不可用,再用n1-->
<!-- 另外一臺服務器配置正好相反,這樣保證將session保存到其它機器,避免整個機器崩潰時tomcat與session一塊兒崩潰-->
<Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
memcachedNodes="n1:192.168.1.62:11211,n2:192.168.1.63:11211"
failoverNodes="n1"
/>
<!-- 常常用到的生產環境sticky模式配置 -->
<Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
memcachedNodes="n1:192.168.1.62:11211,n2:192.168.1.63:11211"
failoverNodes="n1"
requestUriIgnorePattern=".*\.(jpg|png|css|js)$"
memcachedProtocol="binary"
transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory"
/>
<!-- 常常用到的生產環境non-sticky模式配置 -->
<Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
memcachedNodes="n1:192.168.1.62:11211,n2:192.168.1.63:11211"
sticky="false"
sessionBackupAsync="false"
lockingMode="auto"
requestUriIgnorePattern=".*\.(jpg|png|css|js)$"
memcachedProtocol="binary"
transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory"
/>
<!--
<Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
memcachedNodes="n1:192.168.1.62:11211,n2:192.168.1.63:11211"
#sticky模式,默認true
sticky="false"
#僅適用於sticky模式,n1表示主要將session備份到n2,若是n2不可用,再用n1
failoverNodes="n1"
#忽略的請求類型,這些類型請求不處理session
requestUriIgnorePattern=".*\.(jpg|png|css|js)$"
#例如context中設置sessionPath=/時,一個host下多個應用可能有相同session_id,
#此時向memcached寫入時會形成混亂,可經過如下方式加前綴區分不一樣應用
storageKeyPrefix="static:name|context|host|webappVersion|context.hash|host.hash|多項組合,以,間隔"
#設置mecached協議數據傳輸方式,默認text,設爲binary有助力性能提高
memcachedProtocol="binary"
#是否異步存儲session變化,默認true,性能好,適用於sticky模式,
#non-sticky時建議設置爲false,避免延遲形成信息不一致
sessionBackupAsync="false"
#僅適用於non-sticky模式,爲避免同步編輯衝突,在修改session時鎖定
#同步編輯一種可能發生的狀況是在ajax請求時,同一頁多個請求同時發起,可能會訪問不一樣後端
#auto 讀模式不鎖寫模式鎖
#uriPattern模式,將URI+"?"+queryString與模式Regex匹配,若是匹配則鎖定
lockingMode="none|all|auto|uriPattern:Regex"
#使用第三方序列化工具,提升序列化性能
#經常使用的第三方工具kryo, javolution, xstream等
#此時須要向tomcat/lib下添加相關jar包
transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory"
/>
-->
</Context>
Serialable
接口)request.getRemoteAddr()
方法獲取的是nginx代理的地址,若是須要知道客戶端的IP,須要在nginx中設置代理的頭信息。location / {
# root html;
index index.html index.htm;
# 將請求轉交給tomcat集羣
proxy_pass http://tomcats;
# 設置代理的頭信息
proxy_set_header X-Real-IP $remote_addr;
}
在咱們的應用中能夠這樣獲取客戶端的真實IP:
public class RealGetter{
/**
* 有X-Real-IP頭,就獲取X-Real-IP,不然request.getRemoteAddr()
*/
public String getIP(HttpServletRequest request){
String remoteIP = request.getRemoteAddr();
String headIP = request.getHeader('X-Real-IP');
return headIP == null ? remoteIP : headIP;
}
}
# 清除全部規則
iptables -F
# 重啓iptables
service iptables restart
關閉SELinux
vim /etc/selinux/config
#SELINUX=enforcing #註釋掉
#SELINUXTYPE=targeted #註釋掉
SELINUX=disabled #增長
setenforce 0 #使配置當即生效