openresty 限流 (redis+lua) 备忘,openrestyredis


githunb上下载lua-resty-limit-traffic 

解压到/usr/openv/servers/lualib/restylimit目录下。 servers 为openresty安装目录.

/usr/openv/servers/nginx/conf/lua目录

新建limit.lua  

local limit_req = require "resty.limit.req"
   local redis = require "resty.redis"
   local instance = redis.new();
    instance.connect(instance,'127.0.0.1','6379')
   local rate =tonumber(instance:get("limitrate"))
    local burst =tonumber(instance:get("limitburst"))
    --local rate=3 这里如果不用redis 可以直接使用rate=3进行赋值
    --local burst =10
    local error_status = 503
   local nodelay = false
   local lim, err = limit_req.new("limit_req_store", rate, burst)
  if not lim then
       ngx.exit(error_status)
   end
   
   local key = ngx.var.binary_remote_addr
  
   local delay, err = lim:incoming(key, true)
   
   if not delay and err == "rejected" then
       ngx.exit(error_status)
   end
   
   if delay > 0 then
       if nodelay then
   
       else
           ngx.sleep(delay)
      end
   end

/usr/openv/servers/nginx/conf

lua.conf

 server { 
    listen 80; 
    server_name _; 


 location /limit {
              access_by_lua_file conf/lua/limit.lua;
              
               default_type 'text/html';
                   lua_code_cache off;
                   content_by_lua 'ngx.say("hello world")';
                #   proxy_pass http://proxy/_cat/master;
                #     proxy_redirect  off;
            #   proxy_set_header        Host    $http_host;
          # proxy_set_header        X-Real-IP       $remote_addr;
          #  proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
          #     proxy_set_header   Cookie $http_cookie;
 
 }
}



/usr/openv/servers/nginx/conf

nginx.conf 中增加:


 http {
      include       mime.types;
 include lua.conf;
 default_type  application/octet-stream;
 lua_package_path "/usr/servers/lualib/?.lua;;";
 lua_package_cpath "/usr/servers/lualib/?.so;;";
 lua_shared_dict limit_req_store 10m;




相关内容

    暂无相关文章