手机版
你好,游客 登录 注册
背景:
阅读新闻

Nginx之扩展Web服务器OpenResty的初步应用

[日期:2013-02-19] 来源:Linux社区  作者:haoyun [字体:大 中 小]
方法二
 
1、修改 nginx 配置文件 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;
root html;
index index.html index.htm;
location / {
content_by_lua '
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)

local ok,err,errno,sqlstate = db:connect{
host = "127.0.0.1",
port = 3306,
database = "test",
user = "root",
password = "",
max_package_size = 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("select id,username,age from users where id=1")
if not res then
ngx.say("bad result: ", err, ": ", errno, ": ", sqlstate, ".")
return
end

local cjson = require "cjson"
ngx.say("result: ",cjson.encode(res))
';
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
2、测试配置文件、重启 nginx 服务
[root@vm5 conf]# /usr/local/openresty/nginx/sbin/nginx -t -c /usr/local/openresty/nginx/conf/nginx.conf
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
[root@vm5 conf]# killall -HUP nginx
3、测试
[root@vm5 conf]# curl localhost
connected to mysql.
result: [{"username":"zhangsan","age":24,"id":1}]
ok,输出json格式数据了,结果也是对的。赞一个!
 
我们稍作修改,使其支持传递 id 参数
修改 nginx 配置文件
res,err,errno,sqlstate = db:query("select id,username,age from users where id="..ngx.var.arg_id)
测试配置、重启服务,略
测试结果
[root@vm5 conf]# curl localhost/?id=2
connected to mysql.
result: [{"username":"lisi","age":26,"id":2}]
[root@vm5 conf]# curl localhost/?id=1
connected to mysql.
result: [{"username":"zhangsan","age":24,"id":1}]
再一次ok,效果不错吧!
 
注意:以上代码要想用在生产环境,还需要添加一些错误捕获代码!
 
这里有些代码是参照官网上的,详情可以查阅官网。
linux
相关资讯       Nginx  OpenResty 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款