用Nginx+Lua+Redis給百度鷹眼API服務搭建緩存服務中間件(記錄過程)

1、環境安裝部分html

Centos7,Nginx1.14,Redis5.0,luajit-2.1,ngx_devel_kit-0.3.1rc1,lua-nginx-module-0.10.14.nginx

下載安裝包:git

wget http://nginx.org/download/nginx-1.14.0.tar.gz
wget https://github.com/simplresty/ngx_devel_kit/archive/v0.3.1rc1.tar.gz
wget https://github.com/openresty/lua-nginx-module/archive/v0.10.14.tar.gz
wget http://luajit.org/download/LuaJIT-2.1.0-beta3.tar.gz
wget http://download.redis.io/releases/redis-5.0.4.tar.gzgithub

安裝配置過程:redis

解壓ngx_devel_kit和lua-nginx-modulejson

tar xzvf v0.3.1rc1.tar.gz
tar xzvf v0.10.14.tar.gzapi

解壓LuaJIT,進入目錄編譯安裝
緩存

make PREFIX=/usr/local/luajit
make install PREFIX=/usr/local/luajit
export LUAJIT_LIB=/usr/local/luajit/lib
export LUAJIT_INC=/usr/local/luajit/include/luajit-2.1app

解壓Nginx,給編譯參數追加上面三個模塊的目錄再編譯dom

nginx -V #已安裝Nginx執行該命令查看現有編譯參數
configure arguments: 
--prefix=/usr/local/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --user=www --group=www --with-http_ssl_module --with-pcre --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module

#執行./configure命令,在現有編譯參數最後追加luajit,ngx_devel_kit和lua-nginx-module
./configure --prefix=/usr/local/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --user=www --group=www --with-http_ssl_module --with-pcre --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module--with-ld-opt=-Wl,-rpath,/usr/local/luajit/lib --add-module=/data/lua/ngx_devel_kit-0.3.1rc1 --add-module=/data/lua/lua-nginx-module-0.10.14

service nginx stop
make #編譯
cp objs/nginx /usr/sbin/
service nginx start
nginx -V #檢查模塊是否添加上

 

解壓Redis,進入目錄編譯

make PREFIX=/usr/local/redis
make install PREFIX=/usr/local/redis
cd /usr/local/redis/bin
./redis-server & #啓動
./redis-cli #測試set a a; keys *; flushall

 


 

 

2、Lua代碼編寫部分

下載插件拷貝lua文件至目錄 /usr/local/lib/lua/resty
resty.http:https://github.com/ledgetech/lua-resty-http
resty.redis:https://github.com/openresty/lua-resty-redis
resty.redis_iresty:https://github.com/moonbingbing/9915c66346e8fddcefb5

配置Nginx文件

#http下添加lua路徑
lua_package_path "/usr/local/lib/lua/?.lua;;";

#server下添加DNS,字符集和location
resolver 8.8.8.8;
charset utf-8;
#地理解碼
location /geocoder/{
  default_type "application/json;charset=utf-8";
  content_by_lua_file "/usr/local/lib/lua/resty/geocoder.lua"
  #也能夠用content_by_lua_block{直接將代碼寫到nginx內部}
}
#鷹眼服務
location /api/ {
  default_type "application/json;charset=utf-8";
  content_by_lua_file "/usr/local/lib/lua/resty/api.lua"
}

編寫lua代碼文件

地理解碼文件/usr/local/lib/lua/resty/geocoder.lua
數據隱私保護:客戶端發送請求url能夠不須要攜帶ak和service_id參數
二次請求緩存:第二請求傳遞座標數據時,直接從redis拿座標對應位置

local url = ngx.var.request_uri.."&ak=你的ak參數&service_id=你的鷹眼服務id"
local redis = require "resty.redis_iresty"
local red = redis:new()
local res, err = red:get(url)
if not res or res == ngx.null then
    local http = require "resty.http"
    local httpc = http.new()
    local res, err = httpc:request_uri("http://api.map.baidu.com"..url)
    if res.status == ngx.HTTP_OK then
        red:set(url, res.body)
        ngx.print(res.body)
        return
    else
        ngx.exit(res.status)
    end
end

ngx.print(res)

 

鷹眼服務API文件/usr/local/lib/lua/resty/api.lua
支持post請求,可編輯post參數內容,對post參數追加ak和service_id
爲防止錯亂,只對包含參數end_time且值小於今天的請求結果進行緩存
客戶端可用http://yourdomain.com/api/* 代替 http://yingyan.baidu.com/api/*

local http = require "resty.http"
local httpc = http.new()

if ngx.var.request_method == "POST" then
    ngx.req.read_body();
    local postargs = ngx.req.get_post_args()
    local postdata = "ak=你的ak參數&service_id=你的鷹眼服務id"
    for k,v in pairs(postargs) do
        postdata = postdata.."&"..k.."="..v
    end
    local res = httpc:request_uri("http://yingyan.baidu.com"..ngx.var.uri, { method = "POST", body = postdata, headers = { ["Content-Type"] = "application/x-www-form-urlencoded", ["Content-Length"] = nil } })
    if res.status == ngx.HTTP_OK then
        ngx.print(res.body)
        return
    else
        ngx.exit(res.status)
    end
end

local end_time = nil
local args = ngx.req.get_uri_args()
local url = ngx.var.request_uri.."&ak=你的ak參數&service_id=你的鷹眼服務id"
for k,v in pairs(args) do
    if(k == "end_time") then
        end_time = v
        break
    end
end
if(end_time ~= nil) then
    local now_time = os.date("*t")
    local today_time = os.time({day=now_time.day, month=now_time.month,year=now_time.year, hour=0, minute=0, second=0})
    if(tonumber(end_time) < today_time) then
        local redis = require "resty.redis_iresty"
        local red = redis:new()
        local res = red:get(url)
        if not res or res == ngx.null then
            local res = httpc:request_uri("http://yingyan.baidu.com"..url)
            if res.status == ngx.HTTP_OK then
                red:set(url, res.body)
                ngx.print(res.body)
                return
            else
                ngx.exit(res.status)
            end
        end

        ngx.print(res)
        return
    end
end

local res = httpc:request_uri("http://yingyan.baidu.com"..url)
if res.status == ngx.HTTP_OK then
    ngx.print(res.body)
else
    ngx.exit(res.status)
end

以上開發調試工具:https://openresty.org/download/openresty-1.13.6.2-win64.zip,https://moonbingbing.gitbooks.io/openresty-best-practices/content/lua/build_env.html

PS:原創文章,轉載請標註來源。@輕雲科技,by海飛。

相關文章
相關標籤/搜索