OpenResty

OpenResty

起男 717 2021-09-06

OpenResty

上手

  1. 修改配置文件nginx.conf

    worker_processes  1;
    
    events {
        worker_connections  1024;
    }
    
    
    http {
        include       mime.types;
        default_type  application/octet-stream;
    
        sendfile        on;
    
        keepalive_timeout  65;
    	#加载lua模块
    	lua_package_path "D:\openResty\openresty-1.19.9.1-win64\lualib\?.lua;;";
    	#加载c模块
    	lua_package_cpath "D:\openResty\openresty-1.19.9.1-win64\lualib\?.so;;";
    
        server {
            listen       80;
            server_name  localhost;
    
    		location /api {
    			#相应类型
    			default_type application/json;
    			#相应数据由lua文件决定
    			content_by_lua_file lua/api.lua;
    		}
        }
    }
    
  2. 编辑lua文件

    ngx.say('{"data":"hello openresty"}')
    
  3. 启动openresty

获取请求参数

openresty提供了各种api来获取不同类型的请求参数

参数格式参数示例代码示例
路径占位符/user/1nginx.config:location ~/user/(\d+){}
lua:ngx.var[1]
请求头id:1ngx.req.get_headers()
get请求参数?id=1ngx.req.get_uri_args()
post表单参数id=1读取请求体:ngx.req.read_body()
ngx.req.get_post_args()
json参数{"id":1}读取请求体:ngx.req.read_body()
ngx.req.get_body_data()

除了路径占位符以外其它的返回值都是table

内部发送http请求

local resp = ngx.location.capture("/path",{ -- 请求路径,并不包含ip和端口。这个请求会被nginx内部的server监听并处理
        method = ngx.HTTP_GET, --请求方式
        args = {a=1,b=2}, -- get方式传递参数
        body = "c=3&d=4" --post方式传递参数
    })

相应内容

  • resp.status:响应状态码
  • resp.header:响应头,是一个table
  • resp.body:响应体,就是响应数据

自定义函数

  1. 在lua文件夹下创建.lua文件,并在文件中封装自定义函数

  2. 在其它lua文件使用时

    --导入函数库
    local funs = require("相对路径")
    --获取具体函数
    local f1 = funs.f1
    --使用
    f1('xxx')
    

json转换

使用openresty提供的cjson

  1. 导入cjson

    local cjson = require('cjson')
    
  2. 序列化

    local json = cjson.encode(obj)
    
  3. 反序列化

    local obj = cjson.decode(json)
    

其它api

api功能
ngx.log()打印日志
ngx.exit()退出并返回状态码