安裝lua
有linux版本的安裝也有mac版本的安裝。。我們採用linux版本的安裝,首先我們準備一個linux虛擬機。
安裝步驟,在linux系統中執行下面的命令。
//下載
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
此時再執行lua測試看lua是否安裝成功
[root@localhost ~]# lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio</pre>
安裝openresty
linux安裝openresty:
1.添加倉庫執行命令
yum install yum-utils
yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
2.執行安裝
yum install openresty
3.安裝成功後 會在默認的目錄如下:
/usr/local/openresty
測試訪問
重啓下centos虛擬機,然後訪問測試Nginx
訪問地址:http://192.168.200.128/
lua腳本從數據庫查詢數據到redis,創建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()
//地址傳來的參數
local position = uri_args["position"]
local db = mysql:new()
db:set_timeout(10000)
local props = {
host = "192.168.200.128",
port = 3306,
database = "數據庫名",
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}")
數據從redis到nginx,創建read_ad.lua
--設置響應頭類型
ngx.header.content_type="application/json;charset=utf8"
--獲取請求中的參數ID
local uri_args = ngx.req.get_uri_args();
local position = uri_args["position"];
--獲取本地緩存
local cache_ngx = ngx.shared.dis_cache;
--根據ID 獲取本地緩存數據
local adCache = cache_ngx:get('ad_cache_'..position);
if adCache == "" or adCache == nil then
--引入redis庫
local redis = require("resty.redis");
--創建redis對象
local red = redis:new()
--設置超時時間
red:set_timeout(2000)
--連接
local ok, err = red:connect("192.168.200.128", 6379)
--獲取key的值
local rescontent=red:get("ad_"..position)
--輸出到返回響應中
ngx.say(rescontent)
--關閉連接
red:close()
--將redis中獲取到的數據存入nginx本地緩存
cache_ngx:set('ad_cache_'..position, rescontent, 10*60);
else
--nginx本地緩存中獲取到數據直接輸出
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 突發情況下 允許訪問4個請求
limit_req zone=adRateLimit burst=4 nodelay;
content_by_lua_file /usr/local/openresty/lua/read_ad.lua;
}
}
如果要嘗試訪問可將前端頁面放到/usr/local/openresty/nginx/html
下。