OpenResty + Lua + Redis 實現 客戶端ip防刷

一、環境說明:

在Centos7上安裝openresty
此次安裝採用的是下載openresty的yum源來安裝

[root@kusou-es11 conf]# sudo  yum-config-manager --add-repo https://openresty.org/yum/cn/centos/OpenResty.repo

sudo:yum-config-manager:找不到命令
解決辦法:

[root@kusou-es11 conf]# yum -y install yum-utils

下載Openresty的yum源:

[root@kusou-es11 conf]# sudo yum-config-manager --add-repo https://openresty.org/yum/cn/centos/OpenResty.repo
已加載插件:fastestmirror
Repository epel is listed more than once in the configuration
Repository epel-debuginfo is listed more than once in the configuration
Repository epel-source is listed more than once in the configuration
adding repo from: https://openresty.org/yum/cn/centos/OpenResty.repo
grabbing file https://openresty.org/yum/cn/centos/OpenResty.repo to /etc/yum.repos.d/OpenResty.repo
repo saved to /etc/yum.repos.d/OpenResty.repo

安裝命令:


 yum install openresty openresty-resty openresty-opm  
[root@kusou-es11 conf]#  yum install openresty openresty-resty openresty-opm

Running transaction
  正在安裝    : openresty-zlib-1.2.11-3.el7.centos.x86_64                                                                                                                                  1/7 
  正在安裝    : openresty-openssl-1.1.0h-3.el7.centos.x86_64                                                                                                                               2/7 
  正在安裝    : openresty-pcre-8.42-1.el7.centos.x86_64                                                                                                                                    3/7 
  正在安裝    : openresty-1.15.8.1-1.el7.x86_64                                                                                                                                            4/7 
  正在安裝    : openresty-resty-1.15.8.1-1.el7.noarch                                                                                                                                      5/7 
  正在安裝    : openresty-doc-1.15.8.1-1.el7.noarch                                                                                                                                        6/7 
  正在安裝    : openresty-opm-1.15.8.1-1.el7.noarch            
[root@kusou-es11 openresty]# which openresty
/usr/bin/openresty
[root@kusou-es11 openresty]# openresty -v
nginx version: openresty/1.15.8.1

到此處安裝完成

[root@kusou-es11 openresty]# ls
bin  COPYRIGHT  luajit  lualib  nginx  openssl  pcre  pod  resty.index  site  zlib
[root@kusou-es11 openresty]# pwd
/usr/local/openresty

二、防刷和限流概念介紹:

防刷的概念:
防刷的目的是爲了防止有些IP來爬去我們的網頁,獲取我們的價格等信息。不像普通的搜索引擎,這種爬去行爲我們經過統計最高每秒300次訪問,平均每秒266次訪問。
由於我們的網站的頁面都在CDN上,導致我們的CDN流量會定時冒尖。爲了防止這種情況,打算將網頁頁面的訪問從CDN切回主站。同時開啓防刷功能,目前設置一秒200次訪問即視爲非法,會阻止10分鐘的訪問。

限流的概念
限流的目的是在大促或者流量突增期間,我們的後端服務假設某個接口能夠扛住的的QPS爲10000,這時候同時有20000個請求進來,經過限流模塊,會先放10000個請求,其餘的請求會阻塞一段時間。不簡單粗暴的返回404,讓客戶端重試,同時又能起到流量銷峯的作用。

原文出處:https://blog.csdn.net/fenglvming/article/details/51996406 此處簡單引用,入涉及侵權,及時通知刪除

三、客戶端ip防刷具體實現


[root@VM_82_178_centos redislua]# cat /usr/local/openresty/nginx/conf/redislua/ipblack.lua 
--Lua
--定義關閉redis函數:
local function close_redis(red)
    if not red then
        return
    end
    -- 釋放連接(連接池實現),毫秒
    local pool_max_idle_time = 10000 
    -- 連接池大小
    local pool_size = 100 
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
    local log = ngx_log
    if not ok then
        log(ngx_ERR, "set redis keepalive error : ", err)
    end
end

-- 連接redis
local redis = require('resty.redis')
local red = redis.new()
      red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", 20108)
    if not ok then
        ngx.say("failed to connect: ", err)
        return
    end

    local res, err = red:auth("123456")
    if not res then
        ngx.say("failed to authenticate: ", err)
        return
    end

--獲取客戶端真實的ip:
local clientIP = ngx.req.get_headers()["X-Real-IP"]
if clientIP == nil then
   clientIP = ngx.req.get_headers()["x_forwarded_for"]
end
if clientIP == nil then
   clientIP = ngx.var.remote_addr
end

--定義redis key值格式,incrkey 請求的頻率,blockKey被阻塞的key,後面會存入redis:

local incrKey = "user:"..clientIP..":freq"
local blockKey = "user:"..clientIP..":block"

local is_block,err = red:get(blockKey) -- check if ip is blocked
if tonumber(is_block) == 1 then
    ngx.exit(403)
    close_redis(red)
end

--incr redis操作 默認是從0開始,執行一次會累加1
inc  = red:incr(incrKey)

if inc < 10 then
   inc = red:expire(incrKey,1)
end
-- 每秒10次以上訪問即視爲非法,會阻止1分鐘的訪問
if inc > 10 then
    --設置block 爲 True 爲1
    red:set(blockKey,1) 
    red:expire(blockKey,60)
end

close_redis(red)

nginx配置文件如下:

[root@VM_82_178_centos redislua]# less /usr/local/openresty/nginx/conf/vhost/01ip-blacklist.conf
server {
     listen       80;
     server_name  01ip-blacklist.com;
      index index.html index.htm index.php;
        root /data/www/test;
     location  / {
     access_by_lua_file   /usr/local/openresty/nginx/conf/redislua/ipblack.lua;
     default_type 'text/html';
     #content_by_lua 'ngx.say("hello world")';
     access_log  /data/wwwlog/01ip_access.log ;
    }  
}

四、測試演示:

ab軟件壓測:
-c10表示併發用戶數爲10
-n10表示請求總數爲10

[root@VM_82_178_centos ~]# ab -c 10 -n 10 'http://01ip-blacklist.com/1.html'

壓測後登錄redis查看redis key值

127.0.0.1:20108> keys *
1) "dog1"
2) "user:119.29.97.131:block"

[root@VM_82_178_centos ~]# curl http://01ip-blacklist.com/1.html
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>openresty</center>
</body>
</html>

過一分鐘恢復,可以正常的請求
[root@VM_82_178_centos limit]# curl http://01ip-blacklist.com/1.html
1234

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章