openresty demo

openresty demo_第1张图片
Screen Shot 2018-05-29 at 4.26.18 PM.png
local mysql = require "resty.mysql"
local cjson = require "cjson.safe"

local tb_concat = table.concat
--数据库查询方法
local function db_query(sql)
    local mysql_db = mysql:new()--new 对象
    mysql_db:set_timeout(1000) --设置超时时间
    local ok, err = mysql_db:connect{ 
        host = "192.168.2.253", --数据库地址
        port = 13301,--数据库端口
        database = "test", --数据库名称
        user = "root",--用户名
        password = "gcstorage", --密码
        charset = "utf8",
        max_packet_size = 1024 * 1024,
    }
    local res, err = mysql_db:query(sql) -- 执行sql语句
    mysql_db:set_keepalive(10000, 100)-- 设置mysql 连接池,用来代替mysql_db:close()
    if not res then
        return nil, err
    end
    return res
end

local http_method =  ngx.req.get_method()  --获取http请求方式
local get_args 
local query
if http_method == "GET" then
    get_args = ngx.req.get_uri_args() -- 获取get 请求的参数

    if  get_args.id then
      query = "select * from tb_test where id = " .. ngx.quote_sql_str(get_args.id)

    end

    if  get_args.name then
      query = "select * from tb_test where name = " .. ngx.quote_sql_str(get_args.name)


    end
    
elseif http_method == "POST" then
    ngx.req.read_body()
    get_args = ngx.req.get_post_args() --获取post请求的参数,该方法只对 x-www-form-urlencoded的类型有用。
    if not get_args.name or not get_args.age then
        ngx.log(ngx.ERR, "body:" .. cjson.encode(get_args))
        ngx.exit(405)
    end
    local sql = {}



    sql[1] = "insert into tb_test (name,age) values ("
    sql[2] = ngx.quote_sql_str(get_args.name)
    sql[3] = ", "
    sql[4] = ngx.quote_sql_str(get_args.age)
    sql[5] = ")"

    query = tb_concat(sql)
    if not get_args.name or not get_args.age then
        ngx.exit(405)
    end
    --get_args = ngx.req.get_body_data()-- 获取任何格式的post请求的参数方法
else
    ngx.log(ngx.ERR, 'http method is wrong!, http:' .. http_method)
    ngx.exit(400)
end
if not get_args or not query then
    ngx.log(ngx.ERR, 'not args:' )
    ngx.exit(400)
end
ngx.log(ngx.ERR, query)
local res, err = db_query(query)
if not res then
    ngx.say(err)
    return
end
ngx.say(cjson.encode(res))
ngx.say(cjson.encode(res))
ngx.say(cjson.encode(res))




worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {
   

   server {
        listen    8080;

  
        lua_code_cache off;

        location /websocket {


            content_by_lua_file "/Users/lzy/www/conf/lua/mysqltest.lua";
        }



    }
}

你可能感兴趣的:(openresty demo)