前言

前段时间,博客和论坛都放到的阿里云新购的三年 T5 实例服务器上,等都转移过去才发现,所谓的 T5 实例只能满足10% 的 CPU 峰值。期间经历了各种卡顿、死机,最终又把博客单独迁移了回来。静态文件走 CDN,文章都 Redis,以为万事大吉了就。

群压

然并卵,有一天,群里有网友说要压测我的论坛,我说那肯定一压一个死,有本事来压我的博客啊,顺手便扔了博客网址,并@了全体人员。

然后,网友齐上阵,十八般武艺都拿出来了,有AB压测的,有使用 jmeter 测试的,更有甚者自己使用 Python、Java 写代码替我压测的,结果就是系统 CPU 爆表,访问博客陷入了漫长的等待。

分析

先说一下博客架构: Nginx + PHP-fpm + CND + Redis + RDS,静态文件走CDN,命中率基本在百分之八九十左右,动态请求走Nginx,然后交给 php-fpm 处理,博客文章进行了缓存处理,查询基本不会走数据库。

这里总结下原因,在网友压测的时候,登录系统,TOP 了一下,发现 PHP-fpm 进程 CPU 占比居高不下,毕竟1C1G的机器配置,相比于Nginx处理静态页面的能力,PHP-fpm 还是太弱鸡了,无论怎么优化,配置总会是瓶颈。

这里说明一下网友的压测,也就算是简单的流量攻击,其实就是模拟多个用户不停的进行访问(访问那些需要大量数据操作,就是需要大量CPU时间的页面),从而把服务压垮。

应对

其实对于压测这种场景,我们使用 OpenResty + Lua 限流就可以轻松解决。

编写 imit_req.lua 脚本:

-- 平滑限制接口请求数 local limit_req = require "resty.limit.req" -- 这里我们使用AB测试,-n访问1000次, -c并发100个 -- ab -n 1000 -c 100 http://121.142.155.213/ -- 限制 ip 每秒只能调用 200 次 接口 ,burst设置为 0 则平滑限流 local lim, err = limit_req.new("my_limit_req_store", 10, 0) if not lim then ngx.log(ngx.ERR, "failed to instantiate a resty.limit.req object: ", err) return ngx.exit(500) end -- IP维度的限流 local key = ngx.var.binary_remote_addr local delay, err = lim:incoming(key, true) if not delay then if err == "rejected" then return ngx.exit(503) end ngx.log(ngx.ERR, "failed to limit req: ", err) return ngx.exit(500) end if delay >= 0.001 then -- the 2nd return value holds the number of excess requests -- per second for the specified key. for example, number 31 -- means the current request rate is at 231 req/sec for the -- specified key. local excess = err -- the request exceeding the 200 req/sec but below 300 req/sec, -- so we intentionally delay it here a bit to conform to the -- 200 req/sec rate. ngx.sleep(delay) -- 延时处理 end 

导入 nginx.conf 配置:

http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; lua_shared_dict my_limit_req_store 100m; lua_shared_dict my_limit_conn_store 100m; lua_shared_dict my_limit_count_store 100m; server{ listen 80; server_name blog.52itstyle.com; index index.php; root /mnt/domains/blog.52itstyle.com; location = /500.html { root /usr/local/openresty/nginx/html; } error_page 500 502 503 504 = /503/503.html; location ~ \.php$ { # 导入 lua 限流 配置 access_by_lua_file /usr/local/openresty/nginx/lua/limit_req.lua; fastcgi_pass 127.0.0.1:9000; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } location ~ /\.ht { deny all; } } 

划重点,脚本中:

# 每秒访问超过2次就拒绝服务,跳转到503错误页面 limit_req.new("my_limit_req_store", 2, 0) 

总结

我经常听卖锁具的人说:“再好的锁,也只防好人,不防坏人!”,同样适用于网络,网友也只是娱乐一下而已,如果真有坏人想搞你,有无数种办法把你搞死死。

参考

http://openresty.org/cn/

https://blog.52itstyle.vip/archives/3608/