nginx的简单使用:负载均衡

nginx:反向代理的服务器;用户发送请求到nginx,nginx把请求发送给真正的服务器,等待服务器处理完数据并返回,再把数据发送给用户。html

nginx做为一个反向代理服务器,能缓存咱们项目的静态文件,并实现反向代理与均衡负载,能够有效减小服务器压力,即便项目不大,也能够使用。nginx

1.创建第一个springboot工程nginx,启动类以下:spring

@RestController
@SpringBootApplication
public class nginxApplication {//implements EmbeddedServletContainerCustomizer{    
    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }    
    public static void main(String[] args) {
        SpringApplication.run(nginxApplication.class, args);  
    }    
//    @Override
//    public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
// 
//        configurableEmbeddedServletContainer.setPort(8090);
//    }
}浏览器

访问:http://localhost:8090/缓存

能够再如图显示:springboot

1.1)修改conf/nginx.conf中的配置文件为:服务器

location / {
            proxy_pass http://localhost:8090/;            
            #root   html;
            #index  index.html index.htm;
        }app

启动cmd,进入有nginx.exe的目录,执行start nginx启动nginx,负载均衡

浏览器访问:http://localhost/    ;如图ide

这样就实现了:用户请求--nginx--服务器

若是没有配置nginx.conf,这是一个欢迎页面。

2.把nginx工程复制为第二个工程nginx2,修改返回的字符串为:Hello World!-----222,为了区分访问到不一样工程

启动访问以下:http://localhost:8091/

2.1)修改conf/nginx.conf中的配置文件为:

再http模块加入:

upstream test{
ip_hash;
server 192.168.1.164:8090 weight=10;#weight:权重
server 192.168.1.164:8091 weight=5;
}

并修改以前修改的

location / {
            proxy_pass http://test;
            #proxy_pass http://localhost:8090;    
            #root   html;
            #index  index.html index.htm;
        }

修改完后,执行nginx.exe -s reload,从新加载配置文件;

再次访问:http://localhost/,刷新几遍能够出现如下图2,若是刷不出来,能够把nginx工程直接关了,或者调整权重。

这样即实现了负载均衡。

参考:https://www.cnblogs.com/zhrxidian/p/5432886.html

完整nginx.conf:

#user  nobody;
worker_processes  3;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    #use  kqueue;#只能用于Linux中
    worker_connections  1024;
}

http {
    
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    #keepalive_timeout  0;
    keepalive_timeout  65;
#weight是权重。集群    
upstream test{
ip_hash;
server 192.168.1.164:8090 weight=10;#server 192.168.1.164:8090/home,会报错,修改后才能够,
server 192.168.1.164:8091 weight=5;
}
    
    server {
        listen       80;
        server_name localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
            
        location / {
            proxy_pass http://test;
            #proxy_pass http://localhost:8090;
            #proxy_pass http://localhost:8091;
            #root   html;
            #index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;       
    }    

}

相关文章
相关标签/搜索