Use lua in nginx to directly access mysql and memcaced to achieve unified Nginx data interface
BitsCN.com
For nginx installation, see nginx + lua + redis to build high-concurrency applications.
Enable nginx nginx_lua_module to support mysql and memcache
Download
Https://github.com/agentzh/lua-resty-memcached
Https://github.com/agentzh/lua-resty-mysql
There are many ways to unify access interfaces. here we will introduce how to use nginx lua to access mysql and cache it with memcache.
The configuration is as follows:
...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)';}...
Second run:
Curl -- gethttp: // app.ca-sim.com/getinfo? Appleid = jfy
mysql found[{"val":"123","tag":"jfy"}]
Run after the second time:
Curl -- gethttp: // app.ca-sim.com/getinfo? Appleid = jfy
memc found[{"val":"123","tag":"jfy"}]
The result is cached.
BitsCN.com