如果是第一次看这个文章,可以先看下这篇openresty介绍性的文章:Openresty概述介绍
在openresty里面可能有访问其他服务的需求,我们当时是需要定时去另外一个服务拉取一些配置信息,然后来改一下配置。实现这个功能需要如下几步操作:
- 编写lua脚本文件,实现http请求
- 添加依赖库源文件到lualib目录
- 拷贝lua代码文件到路径
- 修改nginx.conf文件,添加引入http请求功能
1、编写lua脚本文件
我们命名脚本文件为demo.lua,然后内容如下所示:
local http = require "resty.http"
local json = require "cjson"
local httpc = http.new()
local res, err = httpc:request_uri("http://127.0.0.1:80/getmes",{
method = "GET",
headers = {
-- ["Authorization"] = "Basic YWRtaW46YWRtaW4=",
["Content-Type"] = "application/json",
},
})
if err ~= nil then
ngx.log(ngx.ERR, "httpc:request_uri err = ", err)
return ngx.exit(0)
end
if 200 ~= res.status then
ngx.exit(res.status)
end
--解析返回的数据
local jsondatanew = json.decode(res.body)["data"]
--得到数据进行其他操作
上面的代码中只是在lua代码里面如何发起http请求的操作,这里需要特别注意的是,http请求最好放在init流程中去,其他流程不适合发起http请求,因为响应时间或者其他什么问题,最好不要让http请求参与到访问请求的逻辑中去。本次的演示是将其添加在init_worker_by_lua_file流程中去,是在openresty的启动初始化阶段去做http请求
2、添加依赖库文件
运行的时候缺少resty.http模块的话,需添加几个文件到路径/usr/local/openresty/lualib/resty下面,由于存在以下三个文件,我打包成一个压缩包了,去这下载:http的lua源码依赖库文件下载
3、拷贝lua代码文件
拷贝demo.lua文件到路径/usr/local/openresty/nginx/lua/
4、修改nginx.conf文件
修改nginx.conf文件,在init_worker_by_lua_file流程引入http请求代码,修改nginx.conf文件内容如下:
#user nobody;
worker_processes 1;
error_log logs/error.log error;
error_log logs/error.log notice;
error_log logs/error.log info;
pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# access_log logs/access.log main;
# error_log logs/error.log error;
lua_package_path "/usr/local/openresty/lualib/?.lua;/usr/local/openresty/nginx/lua/?.lua;";
lua_package_cpath "/usr/local/openresty/lualib/?.so;;";
init_worker_by_lua_file lua/demo.lua;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
proxy_connect_timeout 3s;
#gzip on;
# HTTPS server
server {
listen 80;
server_name localhost;
location / {
#设置代理目的url变量
proxy_pass https://127.0.0.1;
}
}
}
lua_package_path "/usr/local/openresty/lualib/?.lua;/usr/local/openresty/nginx/lua/?.lua;";
和
init_worker_by_lua_file lua/demo.lua;
第一句是添加lua代码的路径,第二句代码是指定初始化流程init_worker_by_lua_file会进入demo.lua文件进行http请求的操作,我代码里面目前只是通过http请求获得了body数据,并转成了json格式,数据目前并没使用,你可以拿着数据去实现自己想要的功能。