lua nginx mysql_在nginx中使用lua直接访问mysql和memcaced达到数据接口的统一_MySQL

Nginx

bitsCN.com

安装nginx参见《nginx+lua+redis构建高并发应用》

让nginx 中的nginx_lua_module支持mysql 和memcache

下载

https://github.com/agentzh/lua-resty-memcached

https://github.com/agentzh/lua-resty-mysql

对于访问接口的统一有很多的处理方式,这里介绍使用nginx lua 访问mysql并用memcache缓存起来。

配置如下:...location /getinfo {default_type 'text/plain';content_by_lua 'local args = ngx.req.get_uri_args()if args["appleid"] == nil thenngx.say("param appleid is nil")returnendlocal memcached = require "memcached"local memc, err = memcached:new()if not memc thenngx.say("failed to instantiate memc: ", err)returnendmemc:set_timeout(1000) -- 1 seclocal ok, err = memc:connect("172.16.18.114", 11211)if not ok thenngx.say("failed to connect: ", err)returnendlocal res, flags, err = memc:get(args["appleid"])if err thenngx.say("failed to get memc: ", err)returnendif not res thenlocal mysql = require "mysql"local db, err = mysql:new()if not db thenngx.say("failed to instantiate mysql: ", err)returnenddb:set_timeout(1000) -- 1 seclocal ok, err, errno, sqlstate = db:connect{host = "172.16.18.162",port = 3306,database = "test",user = "root",password = "cpyf",max_packet_size = 1024 * 1024}if not ok thenngx.say("failed to connect: ", err, ": ", errno, " ", sqlstate)returnend-- ngx.say("connected to mysql.")sql = "select * from tagval where tag = /'" .. args["appleid"] .. "/'"res, err, errno, sqlstate = db:query(sql)if not res thenngx.say("bad result: ", err, ": ", errno, ": ", sqlstate, ".")returnendlocal json = require "json"ngx.say("mysql found")ngx.say(json.encode(res))local ok, err = memc:set(args["appleid"], json.encode(res))if not ok thenngx.say("failed to set memc: ", err)returnendlocal ok, err = db:set_keepalive(0, 100)if not ok thenngx.say("failed to set keepalive: ", err)returnendreturnendngx.say("memc found")ngx.say(res)memc:set_keepalive(0, 100)';}...

第二次运行:

curl --gethttp://app.ca-sim.com/getinfo?appleid=jfymysql found[{"val":"123","tag":"jfy"}]

第二次后运行:

curl --gethttp://app.ca-sim.com/getinfo?appleid=jfymemc found[{"val":"123","tag":"jfy"}]

结果已被缓存bitsCN.com

本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉

本文系统来源:php中文网

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值