跳过正文
  1. 文章/
  2. Java/
  3. 组件与中间件/
  4. Nginx/

2、集群的实现,动静分离

·876 字·2 分钟· loading · loading · ·
Java 组件与中间件 Nginx
GradyYoung
作者
GradyYoung
Nginx - 点击查看当前系列文章
§ 2、集群的实现,动静分离 「 当前文章 」

Nginx的使用
#

Nginx启动
#

//在Nginx的目录下使用dos命令
start nginx.exe  #启动nginx
nginx -s reload  #nginx可以重新加载文件
nginx -t #查看配置文件是否有错
nginx -s stop #停止nginx

Nginx整合Tomcat,并实现动静分离(单个Tomcat)
#

修改nginx.conf文件
#

  • listen:表示当前的代理服务器监听的端口,默认的是监听80端口。注意,如果我们配置了多个server,这个listen要配置不一样,不然就不能确定转到哪里去了。
  • server_name:表示监听到之后需要转到哪里去,这时我们直接转到本地,这时是直接到nginx文件夹内。
  • location:表示匹配的路径,这时配置了/表示所有请求都被匹配到这里
  • root:里面配置了root这时表示当匹配这个请求的路径时,将会在这个文件夹内寻找相应的文件,这里对我们之后的静态文件伺服很有用。
  • index:当没有指定主页时,默认会选择这个指定的文件,它可以有多个,并按顺序来加载,如果第一个不存在,则找第二个,依此类推。
server {
    listen 80;
    #为虚拟服务器的识别路径。因此不同的域名会通过请求头中的HOST字段,匹配到特定的server块,转发到对应的应用服务器中去。
    server_name localhost:8080; 
    # proxy_pass:它表示代理路径,相当于转发,而不像之前说的root必须指定一个文件夹
    location / {
        root   html;
        index  index.html index.htm;
        proxy_pass http://localhost:8080;
    } 
    #静态文件交给nginx处理
    location ~ .*\.(js|css|htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$
    {
        root  G:/work/2018/prj04/src/main/webapp;
        expires 30d;
    }
    # 动态请求由反向代理分配去哪儿,见upstream{}
    location ~ .*$ {
        index index;
        proxy_pass http://localhost:8080;
    }
}

配置负载均衡(多个Tomcat)
#

1:启动多个tomcat

2:修改配置文件

#服务器的集群  
upstream  127.0.0.1 {  #服务器集群名字   
    server 127.0.0.1:8082  weight=1;#服务器配置 weight是权重的意思,权重越大,分配的概率越大。  
    server 127.0.0.1:8081  weight=1;  
}

3:修改nginx.conf文件

location / {
    root   html;
    index  index.html index.htm;
    proxy_pass http://127.0.0.1;
    proxy_redirect default;  
}

nginx.conf配置Gateway集群文件实例
#

upstream  gateway {  #服务器集群名字   
    server 127.0.0.1:9000  weight=1;#服务器配置 weight是权重的意思,权重越大,分配的概率越大。  
}

server {
    listen       80;
    server_name gateway;  

    location / {
        root   html;
        index  index.html index.htm /index.html;
        proxy_pass http://localhost:9000;
        proxy_redirect default;
    }
    #静态文件交给nginx处理
    location ~ .*\.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$
    {
            root  G:/Nginx/nginx-1.16.10/nginx-1.16.0/html;
            expires 30d;
    }
}
Nginx - 点击查看当前系列文章
§ 2、集群的实现,动静分离 「 当前文章 」