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;       
    }    

}

相關文章
相關標籤/搜索