Author:Young
Date:2020-07-22

参考链接:
https://maimai.cn/article/detail?fid=1499586218&efid=7sV_7ICGTmBfSDzdd_jmDg&use_rn=1
https://www.cnblogs.com/binghe001/p/13285890.html
https://blog.csdn.net/l1028386804/article/details/107292035
https://www.jianshu.com/p/b340c4c1e164

2.Nginx实现负载均衡、限流、缓存、黑白名单和灰度发布

一、Nginx安装

注意:这里以CentOS 6.8服务器为例,以root用户身份来安装Nginx。

1.安装依赖环境

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

2.安装openssl

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

3.安装pcre

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

4.安装zlib

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 install

5.安装Nginx

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。

二、Nginx负载均衡配置

1.负载均衡配置

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

2.失败重试配置

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限流配置

1.配置参数

limit_req_zone指令设置参数

limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;

limit_req_zone定义在http块中,$binary_remote_addr表示保存客户端IP地址的二进制形式。
Zone定义IP状态及URL访问频率的共享内存区域。zone=keyword标识区域的名字,以及冒号后面跟区域大小。16000个IP地址的状态信息约1MB,所以示例中区域可以存储160000个IP地址。
Rate定义最大请求速率。示例中速率不能超过每秒10个请求。

2.设置限流

location / {limit_req zone=mylimit burst=20 nodelay;proxy_pass http://real_server;
}

burst排队大小,nodelay不限制单个请求间的时间。

3.不限流白名单

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访问是不限流的,其他限流。

IP后面的数字含义:

24表示子网掩码:255.255.255.0
16表示子网掩码:255.255.0.0
8表示子网掩码:255.0.0.0

四、Nginx缓存配置

1.浏览器缓存

静态资源缓存用expire

location ~*  .(jpg|jpeg|png|gif|ico|css|js)$ {expires 2d;
}

Response Header中添加了Expires和Cache-Control,

静态资源包括(一般缓存)

  • 普通不变的图像,如logo,图标等
  • js、css静态文件
  • 可下载的内容,媒体文件

协商缓存(add_header ETag/Last-Modified value)

  • HTML文件
  • 经常替换的图片
  • 经常修改的js、css文件
  • 基本不变的API接口

不需要缓存

  • 用户隐私等敏感数据
  • 经常改变的api数据接口

2.代理层缓存

//缓存路径,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测试/个性化需求时应禁用掉浏览器缓存。

五、Nginx黑名单

1.一般配置

location / {deny  192.168.1.1;deny 192.168.1.0/24;allow 10.1.1.0/16;allow 2001:0db8::/32;deny  all;
}

2. Lua+Redis动态黑名单(OpenResty)

安装运行

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 configurationlocal 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 ) thenlocal 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 thenngx.log(ngx.ERR, "Redis connection error while connect: " .. err);elselocal ok, err = red:auth(redis_pwd)if not ok thenngx.log(ngx.ERR, "Redis password error while auth: " .. err);elselocal new_ip_blacklist, err = red:smembers(redis_key);if err thenngx.log(ngx.ERR, "Redis read error while retrieving ip_blacklist: " .. err);elsengx.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) doip_blacklist:set(banned_ip, true);end-- update timeip_blacklist:set("last_update_time", ngx.now());endendend
endif ip_blacklist:get(ip) thenngx.log(ngx.ERR, "Banned IP detected and refused access: " .. ip);return ngx.exit(ngx.HTTP_FORBIDDEN);
end

六、Nginx灰度发布

1.根据Cookie实现灰度发布

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

2.根据来路IP实现灰度发布

server {……………set $group default;if ($remote_addr ~ "192.168.119.1") {set $group host1;}if ($remote_addr ~ "192.168.119.2") {set $group host2;}

2.Nginx实现负载均衡、限流、缓存、黑白名单和灰度发布相关推荐

  1. Nginx 实现负载均衡、限流、缓存、黑白名单和灰度发布,这是最全的一篇了!

    Nginx]实现负载均衡.限流.缓存.黑白名单和灰度发布,这是最全的一篇了! Nginx安装 注意:这里以CentOS 6.8服务器为例,以root用户身份来安装Nginx. 1.安装依赖环境 yum ...

  2. 【Nginx】实现负载均衡、限流、缓存、黑白名单和灰度发布,这是最全的一篇了!(建议收藏)

    大家好,我是冰河~~ 在<[高并发]面试官问我如何使用Nginx实现限流,我如此回答轻松拿到了Offer!>一文中,我们主要介绍了如何使用Nginx进行限流,以避免系统被大流量压垮.除此之 ...

  3. kong插件应用(熔断 限流,黑白名单,认证(basic,key,jwt,hmac,),授权,加密,zipkin链路跟踪,日志, prometheus可视化, 爬虫控制插件)

    全栈工程师开发手册 (作者:栾鹏) 架构系列文章 kong安装部署以及kong-dashboard参考:https://blog.csdn.net/luanpeng825485697/article/ ...

  4. GateWay网关应用案例(跨域、限流、黑白名单)

    Spring Cloud Gateway是基于Spring Boot 2.x,Spring WebFlux和Project Reactor 构建的.属于异步非阻塞架构 Spring Cloud Gat ...

  5. Nginx配置之负载均衡、限流、缓存、黑名单和灰度发布

    Nginx配置之负载均衡.限流.缓存.黑名单和灰度发布 一.Nginx安装(基于CentOS 6.5) 1.yum命令安装 yum install nginx –y (若不能安装,执行命令yum in ...

  6. Nginx 反向代理、负载均衡、页面缓存、URL重写及读写分离详解(1)

    大纲 一.前言 二.环境准备 三.安装与配置Nginx 四.Nginx之反向代理 五.Nginx之负载均衡 六.Nginx之页面缓存 七.Nginx之URL重写 八.Nginx之读写分离 注,操作系统 ...

  7. Nginx 反向代理、负载均衡、页面缓存、URL重写、读写分离及简单双机热备详解...

    大纲 一.前言 二.环境准备 三.安装与配置Nginx  (windows下nginx安装.配置与使用) 四.Nginx之反向代理 五.Nginx之负载均衡  (负载均衡算法:nginx负载算法 up ...

  8. Nginx 反向代理、负载均衡、页面缓存、URL重写及读写分离详解

    标签:读写分离 页面缓存 URL重写 Nginx 反向代理 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://freeloda.bl ...

  9. Nginx 反向代理、负载均衡、页面缓存、URL重写及读写分离详解【转载】

    本文只为备份,以防失效.原文请看https://blog.51cto.com/freeloda/1288553 补充说明:部分图片为测试图片,未完全复制,参考文字描述即可. Nginx 反向代理.负载 ...

最新文章

  1. 一文告诉你,Intellij IDEA神器隐藏的11种实用小技巧!
  2. python常用的集成开发环境有哪些_python IDE有哪些?哪个好用?
  3. sql导航函数 NTH_VALUE
  4. 【译】What is a UTXO, and how does it work for a blockchain ledger?
  5. leetcode最长递增子序列问题
  6. 数据库冷备份和热备份
  7. js substring和substr的区别实例,一目了然
  8. 如何在基于 Intel 的 Mac 上使用机构恢复密钥?
  9. Redis分布式锁之:RedLock
  10. js定义php中变量,JavaScript 变量
  11. 计算机应用基础题excel,计算机应用基础专练习题excel.doc
  12. python编程自然数表达式_实现四则运算 (python实现)by 周乃君 张宏根
  13. glob模块中的glob.glob和golb.iglob
  14. Ubuntu 键盘鼠标失效解决办法
  15. 简洁版Featured Category/Shop by Category模块
  16. GLES2.0中文API-glGetActiveAttrib
  17. 龙光集团:“地王收割机”的近患与隐忧
  18. electron 弹窗
  19. python格式化输出%s、f格式化字符串、print结束语
  20. springboot基于web的在线问答社区系统设计与实现毕业设计源码061628

热门文章

  1. AMX中控IP设置方法
  2. Xshell6 评估期已过——解决办法
  3. 连锁餐饮店、酒店最高效、最省钱的ERP解决方案
  4. AspectJ in Action 第2版 中文目录
  5. JavaScript 反混淆的一般套路和技巧[起][承][转][结]
  6. 用世纪互联Azure账号登录VS2015
  7. 干货| 三大软件架构对比与分析
  8. Visual.Basic程序设计教程题解与上机指导(第四版)pdf
  9. 炒股的智慧:股票投资93条秘籍
  10. 北欧神话和希腊神话中诸神姓名和简介