在nginx中使用lua直接访问mysql和memcaced达到数据接口的统一_MySQL
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在nginx中使用lua直接访问mysql和memcaced达到数据接口的统一_MySQL,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2435字,纯文字阅读大概需要4分钟。
内容图文
![在nginx中使用lua直接访问mysql和memcaced达到数据接口的统一_MySQL](/upload/InfoBanner/zyjiaocheng/581/ef7b3a7a16824a0c8bf1a76532f4d6df.jpg)
安装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 then ngx.say("param appleid is nil") return end local memcached = require "memcached" local memc, err = memcached:new() if not memc then ngx.say("failed to instantiate memc: ", err) return end memc:set_timeout(1000) -- 1 sec local ok, err = memc:connect("172.16.18.114", 11211) if not ok then ngx.say("failed to connect: ", err) return end local res, flags, err = memc:get(args["appleid"]) if err then ngx.say("failed to get memc: ", err) return end if not res then local mysql = require "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 = "172.16.18.162", port = 3306, database = "test", user = "root", password = "cpyf", max_packet_size = 1024 * 1024 } if not ok then ngx.say("failed to connect: ", err, ": ", errno, " ", sqlstate) return end -- ngx.say("connected to mysql.") sql = "select * from tagval where tag = /'" .. args["appleid"] .. "/'" res, err, errno, sqlstate = db:query(sql) if not res then ngx.say("bad result: ", err, ": ", errno, ": ", sqlstate, ".") return end local 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 then ngx.say("failed to set memc: ", err) return end local ok, err = db:set_keepalive(0, 100) if not ok then ngx.say("failed to set keepalive: ", err) return end return end ngx.say("memc found") ngx.say(res) memc:set_keepalive(0, 100) '; } ...
第二次运行:
curl --gethttp://app.ca-sim.com/getinfo?appleid=jfy
mysql found[{"val":"123","tag":"jfy"}]
第二次后运行:
curl --gethttp://app.ca-sim.com/getinfo?appleid=jfy
memc found[{"val":"123","tag":"jfy"}]
结果已被缓存
bitsCN.com内容总结
以上是互联网集市为您收集整理的在nginx中使用lua直接访问mysql和memcaced达到数据接口的统一_MySQL全部内容,希望文章能够帮你解决在nginx中使用lua直接访问mysql和memcaced达到数据接口的统一_MySQL所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。