安裝lua
有l(wèi)inux版本的安裝也有mac版本的安裝本冲。准脂。我們采用linux版本的安裝,首先我們準(zhǔn)備一個linux虛擬機(jī)檬洞。
安裝步驟,在linux系統(tǒng)中執(zhí)行下面的命令狸膏。
//下載
curl -R -O http://www.lua.org/ftp/lua-5.3.5.tar.gz
//解壓
tar zxf lua-5.3.5.tar.gz
cd lua-5.3.5
make linux test
此時再執(zhí)行l(wèi)ua測試看lua是否安裝成功
[root@localhost ~]# lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio</pre>
安裝openresty
linux安裝openresty:
1.添加倉庫執(zhí)行命令
yum install yum-utils
yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
2.執(zhí)行安裝
yum install openresty
3.安裝成功后 會在默認(rèn)的目錄如下:
/usr/local/openresty
測試訪問
重啟下centos虛擬機(jī),然后訪問測試Nginx
訪問地址:http://192.168.200.128/
lua腳本從數(shù)據(jù)庫查詢數(shù)據(jù)到redis疮胖,創(chuàng)建update_ad.lua
ngx.header.content_type="application/json;charset=utf8"
local cjson = require("cjson")
local mysql = require("resty.mysql")
local uri_args = ngx.req.get_uri_args()
//地址傳來的參數(shù)
local position = uri_args["position"]
local db = mysql:new()
db:set_timeout(10000)
local props = {
host = "192.168.200.128",
port = 3306,
database = "數(shù)據(jù)庫名",
user = "root",
password = "root"
}
local res = db:connect(props)
local select_sql = "select url,image from tb_ad where status ='1' and position='"..position.."' and start_time<= NOW() AND end_time>= NOW()"
res = db:query(select_sql)
db:close()
local redis = require("resty.redis")
local red = redis:new()
red:set_timeout(2000)
local ip ="192.168.200.128"
local port = 6379
red:connect(ip,port)
red:set("ad_"..position,cjson.encode(res))
red:close()
ngx.say("{flag:true}")
數(shù)據(jù)從redis到nginx,創(chuàng)建read_ad.lua
--設(shè)置響應(yīng)頭類型
ngx.header.content_type="application/json;charset=utf8"
--獲取請求中的參數(shù)ID
local uri_args = ngx.req.get_uri_args();
local position = uri_args["position"];
--獲取本地緩存
local cache_ngx = ngx.shared.dis_cache;
--根據(jù)ID 獲取本地緩存數(shù)據(jù)
local adCache = cache_ngx:get('ad_cache_'..position);
if adCache == "" or adCache == nil then
--引入redis庫
local redis = require("resty.redis");
--創(chuàng)建redis對象
local red = redis:new()
--設(shè)置超時時間
red:set_timeout(2000)
--連接
local ok, err = red:connect("192.168.200.128", 6379)
--獲取key的值
local rescontent=red:get("ad_"..position)
--輸出到返回響應(yīng)中
ngx.say(rescontent)
--關(guān)閉連接
red:close()
--將redis中獲取到的數(shù)據(jù)存入nginx本地緩存
cache_ngx:set('ad_cache_'..position, rescontent, 10*60);
else
--nginx本地緩存中獲取到數(shù)據(jù)直接輸出
ngx.say(adCache)
end
在/usr/local/openresty/nginx/conf/nginx.conf中添加頭信息环戈,和 location信息
server {
listen 80;
server_name localhost;
location /update_ad {
content_by_lua_file /root/lua/update_ad.lua;
}
location /ad_read {
#使用限流配置 burst 突發(fā)情況下 允許訪問4個請求
limit_req zone=adRateLimit burst=4 nodelay;
content_by_lua_file /usr/local/openresty/lua/read_ad.lua;
}
}
如果要嘗試訪問可將前端頁面放到/usr/local/openresty/nginx/html
下。