当前位置: 首页 > news >正文

【狂神说Java】Nginx详解

✅作者简介:CSDN内容合伙人、信息安全专业在校大学生🏆
🔥系列专栏 :狂神说Java
📃新人博主 :欢迎点赞收藏关注,会回访!
💬舞台再大,你不上台,永远是个观众。平台再好,你不参与,永远是局外人。能力再大,你不行动,只能看别人成功!没有人会关心你付出过多少努力,撑得累不累,摔得痛不痛,他们只会看你最后站在什么位置,然后羡慕或鄙夷。


文章目录

    • 公司产品出现瓶颈?
      • 什么是Nginx?
      • Nginx作用?
      • 正向代理和反向代理:
    • Nginx的安装
      • windows下安装
      • linux下安装
      • Nginx常用命令
    • 演示如何使用:
        • **Nginx可以配置请求转发的服务器的路径:实现http请求获取服务器上的文件,配置静态资源文件**

公司产品出现瓶颈?

我们公司项目刚刚上线的时候,并发量小,用户使用的少,所以在低并发的情况下,一个jar包启动应用就够了,然后内部tomcat返回内容给用户。

但是慢慢的,使用我们平台的用户越来越多了,并发量慢慢增大了,这时候一台服务器满足不了我们的需求了。

于是我们横向扩展,又增加了服务器。这个时候几个项目启动在不同的服务器上,用户要访问,就需要增加一个代理服务器了,通过代理服务器来帮我们转发和处理请求。

我们希望这个代理服务器可以帮助我们接收用户的请求,然后将用户的请求按照规则帮我们转发到不同的服务器节点之上。这个过程用户是无感知的,用户并不知道是哪个服务器返回的结果,我们还希望他可以按照服务器的性能提供不同的权重选择。保证最佳体验!所以我们使用了Nginx。

什么是Nginx?

Nginx (engine x) 是一个高性能的HTTP和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务。Nginx是由伊戈尔·赛索耶夫为俄罗斯访问量第二的Rambler.ru站点(俄文:Рамблер)开发的,第一个公开版本0.1.0发布于2004年10月4日。2011年6月1日,nginx 1.0.4发布。
其特点是占有内存少,并发能力强,事实上nginx的并发能力在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。在全球活跃的网站中有12.18%的使用比率,大约为2220万个网站。
Nginx 是一个安装非常的简单、配置文件非常简洁(还能够支持perl语法)、Bug非常少的服务。Nginx 启动特别容易,并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动。你还能够不间断服务的情况下进行软件版本的升级。
Nginx代码完全用C语言从头写成。官方数据测试表明能够支持高达 50,000 个并发连接数的响应。

Nginx作用?

1:Http代理,反向代理:作为web服务器最常用的功能之一,尤其是反向代理。
2:负载均衡
3:配置前端静态资源文件映射

正向代理和反向代理:

正向代理是代理客户端,反向代理是代理服务器。
而根据这核心的区别,我们也可以记住:代理哪端便可以隐藏哪端。
也就是说:
正向代理隐藏真实客户端,反向代理隐藏真实服务端。
正向代理:翻墙业务

反向代理

**Nginx:**Nginx提供的负载均衡策略有2种:内置策略和扩展策略。
内置策略:轮询,加权轮询,Ip hash。
扩展策略:天马行空,只有你想不到的没有他做不到的。
轮询

加权轮询

iphash对客户端请求的ip进行hash操作,然后根据hash结果将同一个客户端ip的请求分发给同一台服务器进行处理,可以解决session不共享的问题。

上述三种负载均衡策略,后台的服务器连接都是同一个数据库,所以数据是一致的,所有的文件也应该放在文件服务器上。
动静分离:
动静分离: 在我们的软件开发中,有些请求是需要后台处理的,有些请求是不需要经过后台处理的(如:css、html、jpg、js等等文件),这些不需要经过后台处理的文件称为静态文件。让动态网站里的动态网页根据一定规则把不变的资源和经常变的资源区分开来,动静资源做好了拆分以后,我们就可以根据静态资源的特点将其做缓存操作。提高资源响应的速度。

目前,通过使用Nginx大大提高了我们网站的响应速度,优化了用户体验,让网站的健壮性更上一层楼!

Nginx的安装

windows下安装

1、下载nginx
http://nginx.org/en/download.html 下载稳定版本。
以nginx/Windows-1.16.1为例,直接下载 nginx-1.16.1.zip。
下载后解压,解压后如下:

2、启动nginx
有很多种方法启动nginx
(1)直接双击nginx.exe,双击后一个黑色的弹窗一闪而过
(2)打开cmd命令窗口,切换到nginx解压目录下,输入命令 nginx.exe ,回车即可
3、检查nginx是否启动成功
直接在浏览器地址栏输入网址 http://localhost:80 回车,出现以下页面说明启动成功!

4、配置监听
nginx的配置文件是conf目录下的nginx.conf,默认配置的nginx监听的端口为80,如果80端口被占用可以修改为未被占用的端口即可。

这是配置的监听就是我们要访问的地址!当我们监听后,我们访问这个网址时,请求会被转向定义的的服务器列表
当我们修改了nginx的配置文件nginx.conf 时,不需要关闭nginx后重新启动nginx,只需要执行命令 nginx -s reload 即可让改动生效
5、关闭nginx
如果使用cmd命令窗口启动nginx, 关闭cmd窗口是不能结束nginx进程的,可使用两种方法关闭nginx
(1)输入nginx命令 nginx -s stop(快速停止nginx) 或 nginx -s quit(完整有序的停止nginx)
(2)使用taskkill taskkill /f /t /im nginx.exe

taskkill是用来终止进程的,
/f是强制终止 .
/t终止指定的进程和任何由此启动的子进程。
/im示指定的进程名称 .

linux下安装

1、安装gcc
安装 nginx 需要先将官网下载的源码进行编译,编译依赖 gcc 环境,如果没有 gcc 环境,则需要安装:

yum install gcc-c++

2、PCRE pcre-devel 安装
PCRE(Perl Compatible Regular Expressions) 是一个Perl库,包括 perl 兼容的正则表达式库。nginx 的 http 模块使用 pcre 来解析正则表达式,所以需要在 linux 上安装 pcre 库,pcre-devel 是使用 pcre 开发的一个二次开发库。nginx也需要此库。命令:

yum install -y pcre pcre-devel

3、zlib 安装
zlib 库提供了很多种压缩和解压缩的方式, nginx 使用 zlib 对 http 包的内容进行 gzip ,所以需要在 Centos 上安装 zlib 库。

yum install -y zlib zlib-devel

4、OpenSSL 安装
OpenSSL 是一个强大的安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及 SSL 协议,并提供丰富的应用程序供测试或其它目的使用。
nginx 不仅支持 http 协议,还支持 https(即在ssl协议上传输http),所以需要在 Centos 安装 OpenSSL 库。

yum install -y openssl openssl-devel

5、下载安装包
手动下载.tar.gz安装包,地址:https://nginx.org/en/download.html

下载完毕上传到服务器上 /root
6、解压

tar -zxvf nginx-1.18.0.tar.gz
cd nginx-1.18.0


7、配置
使用默认配置,在nginx根目录下执行

./configure
make
make install

查找安装路径: whereis nginx

Nginx常用命令

可以见专门博客

cd /usr/local/nginx/sbin/./nginx  启动./nginx -s stop  停止./nginx -s quit  安全退出./nginx -s reload  重新加载配置文件ps aux|grep nginx  查看nginx进程

启动成功访问 服务器ip:80

注意:如何连接不上,检查阿里云安全组是否开放端口,或者服务器防火墙是否开放端口!
相关命令:

# 开启
service firewalld start
# 重启
service firewalld restart
# 关闭
service firewalld stop
# 查看防火墙规则
firewall-cmd --list-all
# 查询端口是否开放
firewall-cmd --query-port=8080/tcp
# 开放80端口
firewall-cmd --permanent --add-port=80/tcp
# 移除端口
firewall-cmd --permanent --remove-port=8080/tcp
#重启防火墙(修改配置后要重启防火墙)
firewall-cmd --reload
# 参数解释
1firwall-cmd:是Linux提供的操作firewall的一个工具;
2--permanent:表示设置为持久
3--add-port:标识添加的端口;

演示如何使用:

**第一步:**本地启动狂神自己的项目,启动同一个项目2次,并设置使用不同端口,模拟使用多台服务器。
8080:

8081:

**第二步:**我们不能让用户不停的去访问不同的端口号或者服务器,那么我们需要一个代理服务器。
**Nginx:**Nginx提供的负载均衡策略有2种:内置策略和扩展策略。
内置策略:轮询,加权轮询,Ip hash。
扩展策略:天马行空,只有你想不到的没有他做不到的。

**第三步:**进入安装nginx的服务器中,然后修改并配置nginx.conf文件:

# upstream 负载均衡关键字 kuangstudy随便起
upstream kuangstudy{server 127.0.0.1:8080 weight=1; # weight就是权重,默认都是1server 127.0.0.1:8081 weight=1;
}
server {location / {proxy_pass http://kuangstudy;     # 我们通过代理kuangstudy,找到我们真正要请求的服务器。
}

image.png
配置成功后,我们重新启动nginx,重新加载配置文件:
我们访问:http://www.localhost/(即:监听的网址,http默认是80接口),请求会根据proxy_pass进行反向代理(如果直接配置url,直接反向代理到指定的URL,如果配置的是变量,会找upstream配置项(upstream配置项的主要作用是配置多个服务器实现负载均衡),请求被代理到对应的upstream下的服务器上,实现反向代理,加上weight配置可以实现负载均衡。
如果是微服务架构的话,我理解我们反向代理的真正的服务器,应该是网关gateway的服务器,让gateway再去处理分配请求。详见gateway博客

最后的图解:(8080是tomcat的默认端口)

备注:
具体配置文件详解可以看专门博客:Nginx 配置详解 | 菜鸟教程
配置文件解释含义:

########### 每个指令必须有分号结束。#################
#user administrator administrators;  #配置用户或者组,默认为nobody nobody。
#worker_processes 2;  #允许生成的进程数,默认为1
#pid /nginx/pid/nginx.pid;   #指定nginx进程运行文件存放地址
error_log log/error.log debug;  #制定日志路径,级别。这个设置可以放入全局块,http块,server块,级别以此为:debug|info|notice|warn|error|crit|alert|emerg
events {accept_mutex on;   #设置网路连接序列化,防止惊群现象发生,默认为onmulti_accept on;  #设置一个进程是否同时接受多个网络连接,默认为off#use epoll;      #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventportworker_connections  1024;    #最大连接数,默认为512
}
http {include       mime.types;   #文件扩展名与文件类型映射表default_type  application/octet-stream; #默认文件类型,默认为text/plain#access_log off; #取消服务日志    log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定义格式access_log log/access.log myFormat;  #combined为日志格式的默认值sendfile on;   #允许sendfile方式传输文件,默认为off,可以在http块,server块,location块。sendfile_max_chunk 100k;  #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。keepalive_timeout 65;  #连接超时时间,默认为75s,可以在http,server,location块。upstream mysvr {   server 127.0.0.1:7878;server 192.168.10.121:3333 backup;  #热备}error_page 404 https://www.baidu.com; #错误页server {keepalive_requests 120; #单连接请求上限次数。listen       4545;   #监听端口server_name  127.0.0.1;   #监听地址       location  ~*^.+$ {       #请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。#root path;  #根目录#index vv.txt;  #设置默认页proxy_pass  http://mysvr;  #请求转向mysvr 定义的服务器列表deny 127.0.0.1;  #拒绝的ipallow 172.18.5.54; #允许的ip           } }
}

nginx访问另一台服务器上的文件_Dream答案的博客-CSDN博客_nginx 访问另一个服务器文件

Nginx可以配置请求转发的服务器的路径:实现http请求获取服务器上的文件,配置静态资源文件

nginx 中location和root,你确定真的明白他们关系?_果汁华的博客-CSDN博客_nginx中的root
nginx指定文件路径有两种方式root和alias,这两者的用法区别,使用方法总结了下,方便大家在应用过程中,快速响应。root与alias主要区别在于nginx如何解释location后面的uri,这会使两者分别以不同的方式将请求映射到服务器文件上。
root和alias的语法格式:
[root]
语法:root path
默认值:root html
配置段:http、server、location、if
[alias]
语法:alias path
配置段:location
root实例:
location ^~ /t/ {
root /www/root/html/;
}
如果一个请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/t/a.html的文件。

alias实例:
location ^~ /t/ {
alias /www/root/html/new_t/;
}
如果一个请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/new_t/a.html的文件。注意这里是new_t,因为alias会把location后面配置的路径丢弃掉,把当前匹配到的目录指向到指定的目录。
注意:

  1. 使用alias时,目录名后面一定要加"/"。
  2. alias在使用正则匹配时,必须捕捉要匹配的内容并在指定的内容处使用。
  3. alias只能位于location块中。(root可以不放在location中)
    实际项目配置:
 
#user  nobody;
worker_processes  1;#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;#pid        logs/nginx.pid;events {worker_connections  1024;
}stream {upstream pg-server{server 47.99.104.62:5432;}server {listen 5433;proxy_pass pg-server;}
}http {include       mime.types;default_type  application/octet-stream;client_max_body_size  100m;access_log  off;sendfile        on;keepalive_timeout  100;fastcgi_connect_timeout 75;fastcgi_read_timeout 600;fastcgi_send_timeout 600;gzip  on;  gzip_min_length 1k;  gzip_comp_level 4; gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css;  gzip_disable "MSIE [1-6]\."; gzip_vary on; map $http_upgrade $connection_upgrade {default upgrade;'' close;}upstream msc {server  47.99.104.62:18010;}upstream nacos-server {server  47.99.104.62:8848;}upstream graphs {server 47.99.104.62:8000;}upstream websocket-server {server 47.99.104.62:2014;}server {listen       18001;location / {proxy_pass http://nacos-server;}}server {listen       80 default;server_name  localhost;#ssl on;#root ../webapps;#location / {#	rewrite ^/$ /fusionsite-are-basic-web last;#	add_header 'Cache-Control' 'no-cache';#}root ../../Oceansite/webapps/oceansite-basic-web;location = / {#root	../../Oceansite/webapps/oceansite-basic-web;#index  index.html index.htm;rewrite ^/$ /index last;			}location /index {alias	../../Oceansite/webapps/oceansite-basic-web;			}location /login {alias	../../Oceansite/webapps/oceansite-basic-web;			}location /system/menu {alias	../../Oceansite/webapps/oceansite-basic-web/;			}location /RTData/navigation {alias	../../Oceansite/webapps/oceansite-basic-web/;			}location /RTData/flowChart {alias	../../Oceansite/webapps/oceansite-basic-web/;			}location /RTData/47.99.104.62/oceansite-conduction-web {alias	../../Oceansite/webapps/oceansite-basic-web/;			}location /RTData/47.99.104.62/oceansite-video-monitor-web {alias	../../Oceansite/webapps/oceansite-basic-web/;			}location /47.99.104.62/oceansite-ship-record-web {alias	../../Oceansite/webapps/oceansite-basic-web/;			}#记录簿网页资源location /oceansite-ship-record-web {root	../../Oceansite/webapps;	index  index.html index.htm;			}#通导系统网页资源location /oceansite-conduction-web {root	../../Oceansite/webapps;	index  index.html index.htm;			}#视频监控网页资源location /oceansite-video-monitor-web {root	../../Oceansite/webapps;	index  index.html index.htm;			}#视频监控报警照片和视频location /alarmimgdata {root	../../;			}#流程图网页资源location /flowchart {root	../webapps;index  index.html index.htm;			}location /fusionsite-are-basic-web {root	../webapps;index  index.html index.htm;			}location /common {root	../webapps;index  index.html index.htm;			}		#OceanSite 数据接口跳转location /prod-api/ {proxy_read_timeout 86400;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;add_header 'Access-Control-Allow-Credentials' 'true' always;add_header 'Access-Control-Allow-Origin' *; add_header 'Access-Control-Max-Age' 1728000;add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE';add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';proxy_pass http://47.99.104.62:8080/;}location /msc {proxy_pass http://msc;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}location /fusionsite-are-h5-flowchart-web/graph {root ../webapps;}location ~* /fusionsite-are-h5-flowchart-web/graph/.*/Resource/.*\.(jpg|png|jpeg|gif)$ {rewrite ^/fusionsite-are-h5-flowchart-web/graph/(.*)$ /mare-graph/$1 last;}location ~* /mare-graph {root ../App_Server/fusionsite-are-minio-server/data;}location /zrender/src/core/util.js {root ../webapps/fusionsite-are-h5-flowchart-web/graph;}location /graphs/ {proxy_pass http://graphs;proxy_set_header Host 47.99.104.62:8000;}location /msc/fusionsite-are-basic/minIO/fileUpload {proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;add_header 'Access-Control-Allow-Origin' "$http_origin" always;add_header 'Access-Control-Allow-Credentials' 'true' always;add_header 'Access-Control-Allow-Methods' 'POST';add_header 'Access-Control-Allow-Headers' 'lastoperatime,token,DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';proxy_pass http://47.99.104.62:18110/minIO/fileUpload;}location /msc/fusionsite-are-basic/minIO/file/fileUpload {proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;add_header 'Access-Control-Allow-Origin' "$http_origin" always;add_header 'Access-Control-Allow-Credentials' 'true' always;add_header 'Access-Control-Allow-Methods' 'POST';add_header 'Access-Control-Allow-Headers' 'lastoperatime,token,DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';proxy_pass http://47.99.104.62:18110/minIO/file/fileUpload;}location /msc/fusionsite-are-basic/minIO/fileDownload {proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;add_header 'Access-Control-Allow-Origin' "$http_origin" always;add_header 'Access-Control-Allow-Credentials' 'true' always;add_header 'Access-Control-Allow-Methods' 'POST';add_header 'Access-Control-Allow-Headers' 'lastoperatime,token,DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';proxy_pass http://47.99.104.62:18110/minIO/fileDownload;}error_page 404 /404.html;location = /40x.html {}error_page 500 502 503 504 /50x.html;location = /50x.html {}}	server {listen       8000;server_name  localhost;client_max_body_size  100m;location /{root  ../webapps/fusionsite-are-h5-flowchart-web/graph;index  index.html index.htm;}location ~* .*/Resource/.*\.(jpg|png|jpeg|gif)$ {rewrite ^.*/Resource/(.*)$  /resources/$1 last;}location ~* .*/Flows/.*\.(jpg|png|jpeg|gif)$ {rewrite ^.*/Flows/(.*)$  /resources/$1 last;}location /resources {alias ../webapps/fusionsite-are-h5-flowchart-web/resources;}error_page   500 502 503 504  /50x.html;location = /50x.html{root   html;}location /flowchart{proxy_read_timeout 86400;proxy_pass http://websocket-server;proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection $connection_upgrade;}location /graphs/rest {rewrite ^/graphs/(.*)$  /$1 last;}location /rest{proxy_pass http://47.99.104.62:8689/rest;#proxy_redirect off;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;expires off;}}}

文章知识点与官方知识档案匹配,可进一步学习相关知识

相关文章:

  • Nacos热更新
  • 学习c#的第四天
  • 深度解剖Linux权限的概念
  • 关于session的不断变化问题
  • Python:使用marshmallow实现Python数据序列化、反序列化、数据验证
  • 智能一体化管网水位监测仪怎么样?
  • Wireshark抓包(网络分析)工具
  • 机器学习——朴素贝叶斯
  • 利用 Google Artifact Repository 构建docker 镜像仓库
  • C语言左移与右移学习
  • 由浅入深学习统计学 - 常用统计图形学习
  • Stream流的groupingBy
  • 100天精通风控建模(原理+Python实现)——第3天:风控建模中如何处理缺失值?
  • 如何有效的保护Windows登录 安当加密
  • Googletest(Gtest)使用case指南
  • .pyc 想到的一些问题
  • bootstrap创建登录注册页面
  • CentOS7 安装JDK
  • DataBase in Android
  • Docker入门(二) - Dockerfile
  • extjs4学习之配置
  • java2019面试题北京
  • Java编程基础24——递归练习
  • jQuery(一)
  • node.js
  • NSTimer学习笔记
  • python3 使用 asyncio 代替线程
  • Python语法速览与机器学习开发环境搭建
  • vue2.0一起在懵逼的海洋里越陷越深(四)
  • 电商搜索引擎的架构设计和性能优化
  • 服务器从安装到部署全过程(二)
  • 紧急通知:《观止-微软》请在经管柜购买!
  • 思否第一天
  • 移动互联网+智能运营体系搭建=你家有金矿啊!
  • 阿里云ACE认证之理解CDN技术
  • ​Spring Boot 分片上传文件
  • (20050108)又读《平凡的世界》
  • (33)STM32——485实验笔记
  • (6)设计一个TimeMap
  • (附源码)python房屋租赁管理系统 毕业设计 745613
  • (免费领源码)python#django#mysql公交线路查询系统85021- 计算机毕业设计项目选题推荐
  • (三) diretfbrc详解
  • (淘宝无限适配)手机端rem布局详解(转载非原创)
  • (一) springboot详细介绍
  • (转) Face-Resources
  • (转)h264中avc和flv数据的解析
  • (转)微软牛津计划介绍——屌爆了的自然数据处理解决方案(人脸/语音识别,计算机视觉与语言理解)...
  • **登录+JWT+异常处理+拦截器+ThreadLocal-开发思想与代码实现**
  • .gitignore文件---让git自动忽略指定文件
  • .jks文件(JAVA KeyStore)
  • .net 4.0发布后不能正常显示图片问题
  • .NET CORE Aws S3 使用
  • .net 程序 换成 java,NET程序员如何转行为J2EE之java基础上(9)
  • .Net 中Partitioner static与dynamic的性能对比
  • .NET开发不可不知、不可不用的辅助类(一)