OpenResty

安装和简单使用

yum install yum-utils
yum-config-manager --add-repo  https://openresty.org/package/centos/openresty.repo

yum install openresty
默认安装目录/usr/local/openresty

启动openresty
cd /usr/local/openresty/nginx/sbin
./nginx

重启openresty
cd  /usr/local/openresty/nginx/sbin
./nginx -s reload

./nginx -s stop  或者  ./nginx -s quit
stop表示立即停止nginx,不保存相关信息
quit表示正常退出nginx,并保存相关信息
cd /usr/local/openresty/nginx/conf
vi nginx.conf
修改第一行为 user root root;

限流

nginx提供两种限流的方式:
一是控制速率。
二是控制并发连接数。

a、漏桶算法实现控制速率限流
漏桶(Leaky Bucket)算法思路很简单,水(请求)先进入到漏桶里,漏桶以一定的速度出水(接口有响应速率),当水流入速度过大会直接溢出(访问频率超过接口响应速率),然后就拒绝请求,可以看出漏桶算法能强行限制数据的传输速率。

http {
   
    #限流设置 binary_remote_addr根据请求ip限流  binary_ 的目的是压缩内存占用量
    #contentRateLimit缓存命名空间 10m缓存空间大小。
    #rate=2r/s 每秒两个请求。
    limit_req_zone $binary_remote_addr zone=contentRateLimit:10m rate=2r/s;
    server {
        listen       80;
        server_name  localhost;
        location / {
             #使用限流配置
             limit_req zone=contentRateLimit;
             root   html;
             index  index.html index.htm;
         }
    }
}
#zone:定义共享内存区来存储访问信息,1M能存储16000 IP地址的访问信息,10M可以存储16W IP地址访问信息。
#Nginx 实际上以毫秒为粒度来跟踪请求信息,因此 10r/s 实际上是限制:每100毫秒处理一个请求。
#这意味着,自上一个请求处理完后,若后续100毫秒内又有请求到达,将拒绝处理该请求。

处理突发流量:burst
假设rate=10r/s 时,将1s拆成10份,即每100ms可处理1个请求。
**burst=4 **,若同时有4个请求到达,Nginx 会处理第一个请求,剩余3个请求将放入队列。
然后每隔100ms从队列中获取一个请求进行处理。若请求数大于4,将拒绝处理多余的请求,直接返回503。
单独使用 burst 参数并不实用。假设 burst=50 ,rate依然为10r/s,排队中的50个请求虽然每100ms会处理一个,但第50个请求却需要等待 50 * 100ms即 5s。
因此,burst 往往结合 nodelay 一起使用。

http {
    limit_req_zone $binary_remote_addr zone=contentRateLimit:10m rate=2r/s;
    server {
        listen       80;
        server_name  localhost;
        location / {
             #使用限流配置
             limit_req zone=contentRateLimit burst=4 nodelay;
             root   html;
             index  index.html index.htm;
         }
    }
}

如上图,平均每秒允许不超过2个请求,突发不超过4个请求,并且处理突发4个请求的时候,没有延迟,等到完成之后,按照正常的速率处理。
b、控制并发量
ngx_http_limit_conn_module 提供了限制连接数的能力。主要是利用limit_conn_zone和limit_conn两个指令。
注意:并非所有连接都被计算在内,只有当服务器正在处理请求(可以利用sleep)并且已经读取了整个请求头时,才会计算有效连接。

http {	
	limit_conn_zone $binary_remote_addr zone=perip:10m;
	limit_conn_zone $server_name zone=perserver:10m; 
	server {  
	    listen       80;
	    server_name  localhost;
	    location / {
	        limit_conn perip 2;  #单个客户端ip与服务器的连接数。 同一个地址只允许同时连接2次。
	        limit_conn perserver 100; #限制与服务器的总连接数。
	        root   html;
	        index  index.html index.htm;
	    }
	}
}
实际应用
http {
   lua_shared_dict dis_cache 128m;#ngixn缓存模块
   server {
       location /update_content {
            content_by_lua_file /usr/local/lua-5.3.5/update_content.lua;
        }
        location /read_content {
           content_by_lua_file /usr/local/lua-5.3.5/read_content.lua;
        }  
        location /img {
           alias /opt/nginx/img;
           autoindex on;
        } 
   }
}

update_content.lua

ngx.header.content_type="application/json;charset=utf8"
local cjson = require("cjson")
local mysql = require("resty.mysql")

local function close_db(db)
    if not db then
        return
    end
    db:close()
end

local uri_args = ngx.req.get_uri_args()--获取请求参数
local id = uri_args["id"]--获取id

local db,err = mysql:new()
if not db then
    ngx.say("new mysql error:", err)
    return
end
db:set_timeout(1000)
local props = {
    host = "192.168.67.1",
    port = 3306,
    database = "chat",
    user = "root",
    password = "123456"
}

local res,err,errno,sqlstate = db:connect(props)
if not res then
     ngx.say("connect to mysql error :",err, " ,errno :", errno, ",sqlstate :", sqlstate)
     return close_db(db)
end
local select_sql = "select url,pic from tb_content where category_id = '"..id.."' order by sort"
res,err,errno,sqlstate = db:query(select_sql)
if not res then
     ngx.say("select database error:",err, " , errno : ", errno, ", sqlstate : ", sqlstate)
     return close_db(db)
end
close_db(db)

local redis = require("resty.redis")
local red = redis:new()
red:set_timeout(2000)

local ip ="192.168.67.1"
local port = 6379
local password = "redis123"
local ok, err = red:connect(ip,port)
if not ok then
      ngx.say("Cannot connect,host:"..ip..",port: " ..port..",err:"..err)
      return nil
end
local count
count, err = red:get_reused_times()
if 0 == count then
     ok, err = red:auth(password)
     if not ok then
         ngx.say("failed to auth: ", err)
         return nil
     end
elseif err then
     ngx.say("failed to get reused times: ", err)
     return nil
end
red:select(0)
ok, err = red:set("ad_"..id ,cjson.encode(res))
if not ok then --判断操作是否成功
     ngx.say("failed to set value: ", err)
     return
end
-- ok, err = red:set_keepalive(10000, 100) --将连接放入连接池,100个连接,最长10秒的闲置时间
-- if not ok then --判断放池结果
   -- ngx.say("failed to set keepalive: ", err)
   -- return
-- end

ngx.say("{\"flag\":true,\"position\":\""..cjson.encode(res).."\"}")
ok, err = red:close()
   if not ok then
     ngx.say("failed to close: ", err)
     return nil
end

ad_read.lua 有些代码省略了,自行修改。

ngx.header.content_type="application/json;charset=utf8"
local uri_args = ngx.req.get_uri_args();
local id = uri_args["id"];
--获取本地缓存
local cache_ngx = ngx.shared.dis_cache;
--根据ID 获取本地缓存数据
local contentCache = cache_ngx:get('content_cache_'..id);
if contentCache == "" or contentCache == nil then
    local redis = require("resty.redis");
    local red = redis:new()
    red:set_timeout(2000)
    red:connect("192.168.211.132", 6379)
    local rescontent = red:get("content_"..id);

    if ngx.null == rescontent then
        local cjson = require("cjson");
        local mysql = require("resty.mysql");
        local db = mysql:new();
        db:set_timeout(2000)
        local props = {
            host = "192.168.211.132",
            port = 3306,
            database = "tb_content",
            user = "root",
            password = "123456"
        }
        local res = db:connect(props);
        local select_sql = "select url,pic from tb_content where category_id="..id.." order by sort_order";
        res = db:query(select_sql);
        local responsejson = cjson.encode(res);
        red:set("content_"..id,responsejson);
        ngx.say(responsejson);
        db:close()
    else
        cache_ngx:set('content_cache_'..id, rescontent, 10*60);
        ngx.say(rescontent)
    end
    red:close()
else
    ngx.say(contentCache)
end

测试:http://192.168.186.128/update_content?id=1

参考资料:https://github.com/anjia0532/lua-resty-redis-util

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值