通过openresty进行根据接口名称进行接口限流

1.openresty安装

  •  下载openresty
  411  2020-07-01 10:46:03 curl -o openresty-openssl111-1.1.1d-1.x86_64.rpm https://openresty.org/package/opensuse/15.1/x86_64/openresty-openssl111-1.1.1d-1.x86_64.rpm
  413  2020-07-01 10:46:52 curl -o openresty-resty-1.15.8.3-1.x86_64.rpm https://openresty.org/package/opensuse/15.1/x86_64/openresty-resty-1.15.8.3-1.x86_64.rpm
  415  2020-07-01 10:48:05 curl -o openresty-1.15.8.3-1.x86_64.rpm  https://openresty.org/package/opensuse/15.1/x86_64/openresty-1.15.8.3-1.x86_64.rpm
  417  2020-07-01 10:48:53 curl -o openresty-pcre-8.44-1.x86_64.rpm https://openresty.org/package/opensuse/15.1/x86_64/openresty-pcre-8.44-1.x86_64.rpm
  418  2020-07-01 10:49:27 curl -o openresty-zlib-1.2.11-3.x86_64.rpm https://openresty.org/package/opensuse/15.1/x86_64/openresty-zlib-1.2.11-3.x86_64.rpm
  422  2020-07-01 10:51:00 curl -o openresty-openssl-1.1.0l-1.x86_64.rpm  https://openresty.org/package/opensuse/15.1/x86_64/openresty-openssl-1.1.0l-1.x86_64.rpm

下载路径 https://openresty.org/package/opensuse/15.1/x86_64

  •    通过 #rpm -ivh 安装 openresty

2.lua限流脚本编写

 主要部分:
    

    local limit = ngx.shared.limit
    local req
    local total
    if limit then
        req = limit:get(key)   //获得code值为$key的接口访问量
    end
    if req then
        if req >= count then  #如果访问量大于配置的count,告警
                ngx.say("{\"code\":\""..key.."\",\"status\":207,\"message\":\"服务繁忙,请稍后再试!\",\"total\":0,\"data\":[]}")
                return
        end
        limit:incr(key, 1)  #未超配置的访问量次数 则访问量加一
    else
        limit:set(key, 1, seconds)
    end


3.nginx插入限流脚本

location /test {
        default_type 'text/html';
        #进行控制访问速度限制的脚本,写绝对路径
        access_by_lua_file "/home/access_nginx_check.lua";
        content_by_lua_block {
            ngx.say("Hello Lua!")
        }
 }


4.openresty的停止与启动

 nginx -s stop  #停止nginx
 nginx -c .\conf\rate.conf    #启动nginx同时指定配置文件


5.接口限流完成

6.脚本示例地址

https://download.csdn.net/download/growing1224/13129494

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值