OpenResty之连接数据库

1.连接OpenResty的nginx.conf配置

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;
        lua_code_cache off;
        location / {
            root   html;
            index  index.html index.htm;
        }
       location /hello {
            content_by_lua_file ngx_lua/hello.lua;
        }
       location /get_random_string {
            content_by_lua_file ngx_lua/get_random_string.lua;
        }
       location /decode_info {
            content_by_lua_file ngx_lua/decode_info.lua;
        }
       location /redis_hello {
            content_by_lua_file ngx_lua/redis_hello.lua;
        }
       location /mysql_hello {
            content_by_lua_file ngx_lua/mysql_hello.lua;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

2.连接MySQL

local mysql = require "resty.mysql"
local db, err = mysql:new()
if not db then
    ngx.say("failed to instantiate mysql: ", err)
return
end

db:set_timeout(1000)    --1 sec

local ok, err, errno, sqlstate = db:connect{
    host = "127.0.0.1",
    port = 3306,
    database = "test",
    user = "root",
    password = "vagrant",
    max_packet_size = 1024*1024}

if not ok then
    ngx.say("failed to connect: ",err, ":", errno, "  ", sqlstate)
    return
end

ngx.say("connected to mysql.")

res, err, errno, sqlstate = db:query("create table cats"
.. "(id serial primary key, "
.."name varchar(5))")

if not res then
    ngx.say("bad result: ", err, ": ", errno, ":", sqlstate, ".")
    return
end

ngx.say("table cats created.")

res, err, errno, sqlstate = 
    db:query("insert into cats (name) "
    .. "values (\'Bob\'),(\'\'),(null)")

if not res then
    ngx.say("bad result: ", err, ": ", errno, ": ", sqlstate, ".")
    return
end

3.连接Redis

local redis = require "resty.redis"
local red = redis:new()

red:set_timeout(1000)    -- 1 sec

local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
    ngx.say("failed to connect: ", err)
    return
end

ok, err = red:set("dog","an animal")
if not ok then
    ngx.say("failed to set dog: ", err)
    return
end

ngx.say("set result: ", ok)


--put it into the connection pool of size 100
--with 10 seconds max idle time
local ok, err = red:set_keepalive(10000, 100)
if not ok then
    ngx.say("failed to set keepalive: ", err)
    return
end

转载于:https://my.oschina.net/wangjstu/blog/600250

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值