学习使用Nginx配置服务器

Nginx是一个反向代理服务器、负载均衡服务器,同时又能提供缓存服务,本文简单介绍了这三种应用配置。

本文的环境是Windows 10 + nginx-1.18.0,使用VS2019开发ASP.NET Core Web API作为测试服务器。

1、反向代理

Nginx能把浏览器的请求转发到不同的服务器中,因此是一个反向代理服务器。

在nginx.conf中找到http->server节点,配置好监听端口和服务器名称,通过location节点设置代理转发:

listen       8080; #监听端口
server_name  localhost;

location / {
    #root   html;
    #index  index.html index.htm;
    proxy_pass http://WebApi; #设置代理转发,转发到服务器列表
}

然后在http节点配置服务器列表:

#服务器列表
upstream WebApi {
    ip_hash;
    server localhost:6001;
    server localhost:6002 weight=5;
    server localhost:6003 weight=10;
}

这样,对本机的8080端口访问会被转发到6001、6002、6003端口。

2、负载均衡

Nginx的负载均衡有:

  • 轮询
  • weight 权重方式
  • ip_hash 依据ip分配方式
  • least_conn 最少连接方式
  • fair(第三方) 响应时间方式
  • url_hash(第三方) 依据URL分配方式

仅对前面4种做出说明。

轮询是默认负载策略,Nginx会将请求逐一发送到不同的后端服务器。

权重方式在轮询策略的基础上指定轮询的命中几率。在上面的配置中,端口为6003的服务器命中的概率是6001的10倍,是6002的2倍,weight默认值为1。

ip_hash指定按照基于客户端IP的分配方式,相同的客户端的请求一直发送到同一个服务器,以保证session会话。这样每个访客都固定访问一个后端服务器,可以解决session不能跨服务器的问题。

least_conn把请求转发给连接数较少的后端服务器。

需要注意的是,反向代理服务器通过制定的负载均衡策略来转发请求到其中一台服务器上。

参考Nginx服务器之负载均衡策略(6种)

3、缓存

缓存本质是通过键值对来存储数据的,通过对指定的url做一定的算法处理,获取对应的key,将响应结果存储到文件系统中。

缓存通常是伴随着反向代理和负载均衡一起实施的响应速度提升手段。

(1) 设置反向代理缓存的数据缓存地址

http {    
    #设置反向代理缓存的数据缓存地址
    #数据缓存到(当前盘符)D:/Work/Data/Nginx文件夹中,文件夹必须存在。
    proxy_cache_path /Work/Data/Nginx levels=1:2 keys_zone=web_cache:50m inactive=10m max_size=1g;
}

(2) 设置反向代理缓存的key

#设置反向代理缓存的key
location /api/test/ {
    proxy_store off;
    proxy_redirect off;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $http_host;
    proxy_pass http://WebApi/api/test/;
    
    proxy_cache web_cache;
    proxy_cache_valid 200 304 2m;
    proxy_cache_key $scheme$proxy_host$request_uri; #url地址做key
}

(3) 获取最新结果

可以在API后面添加随机参数,比如

http://localhost:8080/api/test/get

可以使用

http://localhost:8080/api/test/get?123456

以获取最新数据。

这是因为使用随机数后缀(本次是123456),和上次访问的URL不一样,因此缓存中没有相同的key,就能够获取最新结果了。

4、运行结果展示

(1) 服务器API代码示例

using Microsoft.AspNetCore.Mvc;
using System;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        [Route("Get")]
        public string Get()
        {
            return $"Get From 6003: {DateTime.Now}";
        }
    }
}

(2) 运行测试服务器

dotnet WebApi.dll --urls="http://*:6001" --ip="127.0.0.1" --port=6001
dotnet WebApi.dll --urls="http://*:6002" --ip="127.0.0.1" --port=6002
dotnet WebApi.dll --urls="http://*:6003" --ip="127.0.0.1" --port=6003

(3) 用浏览器测试服务器

(4) 反复使用代理服务器访问API(结果相同)

(5) Nginx生成的缓存目录

(6) 使用随机数获取最新数据

5、完整的Nginx配置文件

下面是完整配置文件,以供参考。

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


http {
    #设置反向代理缓存的数据缓存地址
    #数据缓存到(在当前盘符的路径下)D:/Work/Data/Nginx文件夹中
    proxy_cache_path /Work/Data/Nginx levels=1:2 keys_zone=web_cache:50m inactive=10m max_size=1g;
    
    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;

    #gzip  on;
    
    #服务器列表
    upstream WebApi {
        ip_hash;
        server localhost:6001 weight=1;
        server localhost:6002 weight=5;
        server localhost:6003 weight=10;
    }

    server {
        listen       8080; #监听端口
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            #root   html;
            #index  index.html index.htm;
            proxy_pass http://WebApi; #设置代理转发,转发到服务器列表
        }
        
        #设置反向代理缓存的key
        location /api/test/ {
            proxy_store off;
            proxy_redirect off;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Host $http_host;
            proxy_pass http://WebApi/api/test/;
            
            proxy_cache web_cache;
            proxy_cache_valid 200 304 2m;
            proxy_cache_key $scheme$proxy_host$request_uri; #url地址做key
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ .php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ .php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}
原文地址:https://www.cnblogs.com/xhubobo/p/14489128.html