OpenResty接口开发,


环境部署

检查当前系统类型 - Ubuntu

# 查看系统版本
$ cat /proc/version
Linux version 4.15.0-46-generic (buildd@lgw01-amd64-038) 
(gcc version 7.3.0 (Ubuntu 7.3.0-16ubuntu3)) 
#49-Ubuntu SMP Wed Feb 6 09:33:07 UTC 2019

检查系统是否已经安装过nginx,若已经安装则停止服务。

# 检查是否已经安装nginx
$ sudo apt install nginx
$ nginx -v
nginx version: nginx/1.14.0 (Ubuntu)

# 检查nginx并关闭
$ sudo systemctl status nginx
$ sudo systemctl disable nginx
$ sudo systemctl stop nginx

# 删除nginx
$ sudo apt-get --purge remove nginx
$ sudo apt-get autoremove
$ ps -ef | grep ngninx
$ sudo apt-get update

安装OpenResty依赖库

# 安装openresty必须的库
$ sudo apt install libreadline-dev libncurses5-dev libpcre3-dev libssl-dev perl make build-essential

openresty安装

# 导入GPG密钥
$ wget -qO - https://openresty.org/package/pubkey.gpg | sudo apt-key add -

# 安装add-apt-repository命令
$ sudo apt-get -y install software-properties-common

# 添加openresty官方的offical API 合集
$ sudo add-apt-repository -y "deb http://openresty.org/package/ubuntu $(lsb_release -sc) main"

# 更新APT索引
$ sudo apt-get update

# 安装openresty
$ sudo apt-get install openresty

openresty默认安装目录

$ cd /usr/local/openresty/
$ ls
bin  COPYRIGHT  luajit  lualib  nginx  openssl  pcre  pod  resty.index  site  zlib

检查openresty版本

$ openresty -v
nginx version: openresty/1.13.6.2

启动openresty的nginx

$ nginx -t
nginx: the configuration file /usr/local/openresty/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/openresty/nginx/conf/nginx.conf test is successful

$ nginx -s reload
$ nginx -p `pwd` -c conf/nginx.conf

每个Nginx进程中都嵌入了一个LuaJIT的虚拟机用来执行Lua脚本,Nginx将Lua脚本的执行交给了LuaJIT的虚拟机LuaVM。

使用openresty的nginx命令作为默认

$ ls -n /usr/local/openresty/nginx/sbin/nginx /usr/bin/nginx

创建openresty的工作目录www,在其中创建logs用于存放日志,创建conf用于存放配置。

$ mkdir -p /www/logs /www/conf /www/lua/ /www/lualib/

编辑nginx.conf配置文件,作用是直接使用openresty输出html页面。

$ vim /www/conf/nginx.conf

user root;

worker_processes 1;

error_log logs/error.log;
pid logs/nginx.pid;

events {
    worker_connections 1024;
}

http {
    server {
        listen 9000;
        location / {
            default_type text/html;
            # content_by_lua 'ngx.say("hello1");';
            content_by_lua_file ./lua/test.lua;
        }
    }
}

Nginx是如何嵌入Lua脚本的呢?方法是在Nginx的配置文件nginx.conf中使用content_by_luacontent_by_lua_file指令。

  • content_by_lua 在简单的Lua脚本时使用
content_by_lua '
  ngx.header.content_type="text/plain";
  ngx.say(ngx.var.test);
';
  • content_by_lua_file适用于复杂的Lua脚本
content_by_lua_file lua/test.lua

在lua文件夹下创建test.lua脚本

$ vim lua/test.lua

local args = ngx.req.get_uri_args()
for k,v in pairs(args) do
   ngx.say("key=",k, " val=",v);
end

启动或重启openresty

$ sudo nginx -p `pwd` -c conf/nginx.conf
$ sudo nginx -p `pwd` -c conf/nginx.conf -s reload
$ sudo /usr/local/openresty/nginx/sbin/nginx -p `pwd` -c ./conf/nginx.conf

测试地址并查看结果

$ curl 127.0.0.1:9000
hello

$ curl 127.0.0.1:9000?key=val
key=key val=val

关闭nginx进程

$ sudo netstat -antup | grep nginx
$ sudo ps -ef|grep nginx
$ sudo kill 9878
$ sudo kill -9 9878
$ sudo killall nginx

接口路由配置

$ vim conf/nginx.lua
user root;

# nginx工作进程数量
worker_processes 1;

# 错误日志文件保存路径
error_log logs/error.log;

# nginx进程编号保存路径
pid logs/nginx.pid;

events {
    worker_connections 1024;
}

# HTTP协议
http {
    # lua文件自动搜索路径
    lua_package_path '$prefix/lua/?.lua;/lualib/?.lua;;';
    
    # 避免每次修改都要重启nginx
    lua_code_cache off;

    # HTTP服务器
    server {
        # 监听端口
        listen 9000;
        # 路由匹配
        location / {
            content_by_lua_block {
                ngx.say('hello world');
                ngx.log(ngx.ERR, 'hello world');
                print([[hell world]]);
            }
            # default_type text/html;
            # content_by_lua 'ngx.say("hello world");';
            # content_by_lua_file test.lua;
        }
        # 接口路径
        location ~ ^/api/([-_a-zA-Z0-9/]+) {
            # 参数验证
            access_by_lua_file lua/validate.lua;
            # 内容生成
            content_by_lua_file lua/$1.lua;
        }
    }
}

在lua文件夹下添加验证文件validate.lua

$ mkdir lua/validate.lua
local utils = require("utils")
-- 接收参数
local args = ngx.req.get_uri_args()
ngx.log(ngx.INFO, args)
if args == nil then
    ngx.exit(ngx.HTTP_BAD_REQUEST)
    return
end

将公共方法添加到lua文件夹下的utils脚本中

$ vim lua/utils.lua
local _M = {}

-- 接收的参数逐个校验
function _M.isNUmber(...)
    local args = {...}
    local number
    for _,v in ipairs(args) do
        number = tonumber(v)
        if number == nil then
            return false
        end
    end
    return true
end

return _M

开启错误日志并使用URL地址进行验证

$ tail -f log/error.log

$ curl 127.0.0.1:9000/api/test?id=10000
key=id val=10000

转载于:https://www.jianshu.com/p/7c3eae65ddc4

相关内容

    暂无相关文章