在《【高并发】面试官问我如何使用Nginx实现限流,我如此回答轻松拿到了Offer!》一文中,咱们主要介绍了如何使用Nginx进行限流,以免系统被大流量压垮。除此以外,Nginx还有不少强大的功能,例如:负载均衡、缓存、黑白名单、灰度发布等。今天,咱们就来一块儿探讨Nginx支持的这些强大的功能!css
注意:这里以CentOS 6.8服务器为例,以root用户身份来安装Nginx。html
yum -y install wget gcc-c++ ncurses ncurses-devel cmake make perl bison openssl openssl-devel gcc* libxml2 libxml2-devel curl-devel libjpeg* libpng* freetype* autoconf automake zlib* fiex* libxml* libmcrypt* libtool-ltdl-devel* libaio libaio-devel bzr libtool
wget https://www.openssl.org/source/openssl-1.0.2s.tar.gz tar -zxvf openssl-1.0.2s.tar.gz cd /usr/local/src/openssl-1.0.2s ./config --prefix=/usr/local/openssl-1.0.2s make make install
wget https://ftp.pcre.org/pub/pcre/pcre-8.43.tar.gz tar -zxvf pcre-8.43.tar.gz cd /usr/local/src/pcre-8.43 ./configure --prefix=/usr/local/pcre-8.43 make make install
wget https://sourceforge.net/projects/libpng/files/zlib/1.2.11/zlib-1.2.11.tar.gz tar -zxvf zlib-1.2.11.tar.gz cd /usr/local/src/zlib-1.2.11 ./configure --prefix=/usr/local/zlib-1.2.11 make make
wget http://nginx.org/download/nginx-1.17.2.tar.gz tar -zxvf nginx-1.17.2.tar.gz cd /usr/local/src/nginx-1.17.2 ./configure --prefix=/usr/local/nginx-1.17.2 --with-openssl=/usr/local/src/openssl-1.0.2s --with-pcre=/usr/local/src/pcre-8.43 --with-zlib=/usr/local/src/zlib-1.2.11 --with-http_ssl_module make make install
这里须要注意的是:安装Nginx时,指定的是openssl、pcre和zlib的源码解压目录,安装完成后Nginx配置文件的完整路径为:/usr/local/nginx-1.17.2/conf/nginx.conf。node
http { …… upstream real_server { server 192.168.103.100:2001 weight=1; #轮询服务器和访问权重 server 192.168.103.100:2002 weight=2; } server { listen 80; location / { proxy_pass http://real_server; } } }
upstream real_server { server 192.168.103.100:2001 weight=1 max_fails=2 fail_timeout=60s; server 192.168.103.100:2002 weight=2 max_fails=2 fail_timeout=60s; }
意思是在fail_timeout时间内失败了max_fails次请求后,则认为该上游服务器不可用,而后将该服务地址踢除掉。fail_timeout时间后会再次将该服务器加入存活列表,进行重试。nginx
limit_req_zone指令设置参数c++
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
location / { limit_req zone=mylimit burst=20 nodelay; proxy_pass http://real_server; }
burst排队大小,nodelay不限制单个请求间的时间。git
geo $limit { default 1; 192.168.2.0/24 0; } map $limit $limit_key { 1 $binary_remote_addr; 0 ""; } limit_req_zone $limit_key zone=mylimit:10m rate=1r/s; location / { limit_req zone=mylimit burst=1 nodelay; proxy_pass http://real_server; }
上述配置中,192.168.2.0/24网段的IP访问是不限流的,其余限流。github
IP后面的数字含义:web
静态资源缓存用expire面试
location ~* .(jpg|jpeg|png|gif|ico|css|js)$ { expires 2d; }
Response Header中添加了Expires和Cache-Control,redis
静态资源包括(通常缓存)
协商缓存(add_header ETag/Last-Modified value)
不须要缓存
//缓存路径,inactive表示缓存的时间,到期以后将会把缓存清理 proxy_cache_path /data/cache/nginx/ levels=1:2 keys_zone=cache:512m inactive = 1d max_size=8g; location / { location ~ \.(htm|html)?$ { proxy_cache cache; proxy_cache_key $uri$is_args$args; //以此变量值作HASH,做为KEY //HTTP响应首部能够看到X-Cache字段,内容能够有HIT,MISS,EXPIRES等等 add_header X-Cache $upstream_cache_status; proxy_cache_valid 200 10m; proxy_cache_valid any 1m; proxy_pass http://real_server; proxy_redirect off; } location ~ .*\.(gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ { root /data/webapps/edc; expires 3d; add_header Static Nginx-Proxy; } }
在本地磁盘建立一个文件目录,根据设置,将请求的资源以K-V形式缓存在此目录当中,KEY须要本身定义(这里用的是url的hash值),同时能够根据须要指定某内容的缓存时长,好比状态码为200缓存10分钟,状态码为301,302的缓存5分钟,其余全部内容缓存1分钟等等。
能够经过purger的功能清理缓存。
AB测试/个性化需求时应禁用掉浏览器缓存。
location / { deny 192.168.1.1; deny 192.168.1.0/24; allow 10.1.1.0/16; allow 2001:0db8::/32; deny all; }
安装运行
yum install yum-utils yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo yum install openresty yum install openresty-resty 查看 yum --disablerepo="*" --enablerepo="openresty" list available 运行 service openresty start
配置(/usr/local/openresty/nginx/conf/nginx.conf)
lua_shared_dict ip_blacklist 1m; server { listen 80; location / { access_by_lua_file lua/ip_blacklist.lua; proxy_pass http://real_server; } }
lua脚本(ip_blacklist.lua)
local redis_host = "192.168.1.132" local redis_port = 6379 local redis_pwd = 123456 local redis_db = 2 -- connection timeout for redis in ms. local redis_connection_timeout = 100 -- a set key for blacklist entries local redis_key = "ip_blacklist" -- cache lookups for this many seconds local cache_ttl = 60 -- end configuration local ip = ngx.var.remote_addr local ip_blacklist = ngx.shared.ip_blacklist local last_update_time = ip_blacklist:get("last_update_time"); -- update ip_blacklist from Redis every cache_ttl seconds: if last_update_time == nil or last_update_time < ( ngx.now() - cache_ttl ) then local redis = require "resty.redis"; local red = redis:new(); red:set_timeout(redis_connect_timeout); local ok, err = red:connect(redis_host, redis_port); if not ok then ngx.log(ngx.ERR, "Redis connection error while connect: " .. err); else local ok, err = red:auth(redis_pwd) if not ok then ngx.log(ngx.ERR, "Redis password error while auth: " .. err); else local new_ip_blacklist, err = red:smembers(redis_key); if err then ngx.log(ngx.ERR, "Redis read error while retrieving ip_blacklist: " .. err); else ngx.log(ngx.ERR, "Get data success:" .. new_ip_blacklist) -- replace the locally stored ip_blacklist with the updated values: ip_blacklist:flush_all(); for index, banned_ip in ipairs(new_ip_blacklist) do ip_blacklist:set(banned_ip, true); end -- update time ip_blacklist:set("last_update_time", ngx.now()); end end end end if ip_blacklist:get(ip) then ngx.log(ngx.ERR, "Banned IP detected and refused access: " .. ip); return ngx.exit(ngx.HTTP_FORBIDDEN); end
根据Cookie查询version值,若是该version值为v1转发到host1,为v2转发到host2,都不匹配的状况下转发到默认配置。
upstream host1 { server 192.168.2.46:2001 weight=1; #轮询服务器和访问权重 server 192.168.2.46:2002 weight=2; } upstream host2 { server 192.168.1.155:1111 max_fails=1 fail_timeout=60; } upstream default { server 192.168.1.153:1111 max_fails=1 fail_timeout=60; } map $COOKIE_version $group { ~*v1$ host1; ~*v2$ host2; default default; } lua_shared_dict ip_blacklist 1m; server { listen 80; #set $group "default"; #if ($http_cookie ~* "version=v1"){ # set $group host1; #} #if ($http_cookie ~* "version=v2"){ # set $group host2; #} location / { access_by_lua_file lua/ip_blacklist.lua; proxy_pass http://$group; } }
server { …………… set $group default; if ($remote_addr ~ "192.168.119.1") { set $group host1; } if ($remote_addr ~ "192.168.119.2") { set $group host2; }
参考:https://github.com/sunshinelyz/ABTestingGateway
好了,我们今天就聊到这儿吧!别忘了给个在看和转发,让更多的人看到,一块儿学习一块儿进步!!
若是你以为冰河写的还不错,请微信搜索并关注「 冰河技术 」微信公众号,跟冰河学习高并发、分布式、微服务、大数据、互联网和云原生技术,「 冰河技术 」微信公众号更新了大量技术专题,每一篇技术文章干货满满!很多读者已经经过阅读「 冰河技术 」微信公众号文章,吊打面试官,成功跳槽到大厂;也有很多读者实现了技术上的飞跃,成为公司的技术骨干!若是你也想像他们同样提高本身的能力,实现技术能力的飞跃,进大厂,升职加薪,那就关注「 冰河技术 」微信公众号吧,天天更新超硬核技术干货,让你对如何提高技术能力再也不迷茫!