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