代码:
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 = "changgou_content",
user = "root",
password = "123456"
}
local res = db:connect(props);
local select_sql = "select url,pic from tb_content where status ='1' and 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
配置的nginx.conf的配置文件
user root root;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#定义Nginx缓存模块,模块名字叫dis_cache,容量大小128M
lua_shared_dict dis_cache 128m;
#限流设置
limit_req_zone $binary_remote_addr zone=contentRateLimit:10m rate=2r/s;
#根据IP地址来限制,存储内存大小10M
limit_conn_zone $binary_remote_addr zone=addr:10m;
#个人IP显示
limit_conn_zone $binary_remote_addr zone=perip:10m;
#针对整个服务所有的并发量控制
limit_conn_zone $server_name zone=perserver:10m;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
#"虚拟机"
server {
listen 80;
#监听的域名
server_name localhost;
#192.168.211.1
location /brand {
limit_conn perip 3; #单个客户端ip与服务器的连接数.
limit_conn perserver 5; #限制与服务器的总连接数
#同一个IP只允许有2个并发连接
#limit_conn addr 2;
#所有以/brand的请求,都将交给 192.168.211.1服务器的18081程序处理.
proxy_pass http://192.168.211.1:18081;
}
#表示所有以 localhost/read_content的请求都由该配置处理
location /read_content {
#使用指定限流配置,burst=4表示允许同时有4个并发连接,如果不能同时处理,则会放入队列,等请求处理完成后,再从队列中拿请求
#nodelay 并行处理所有请求
limit_req zone=contentRateLimit burst=4 nodelay;
#content_by_lua_file:所有请求都交给指定的lua脚本处理(/root/lua/read_content.lua)
content_by_lua_file /usr/local/server/lua65/read_content.lua;
}
#表示所有以 localhost/update_content的请求都由该配置处理
location /update_content {
#content_by_lua_file:所有请求都交给指定的lua脚本处理(/root/lua/update_content.lua)
content_by_lua_file /usr/local/server/lua65/update_content.lua;
}
}
}