Nginx通过Lua访问Memcache

一、安装OpenResty
请参看《Nginx 1.4.3.6 + PHP 5.4.25(FastCGI)在CentOS 6.4下的编译安装
二、编写Lua代码

vi /usr/local/webserver/nginx/conf/nginx.conf


新建一个用于测试的虚拟主机,实现访问http://testlua.com/hello的时候,通过ua做key到memcache中查找value并输出。

  server
  {
    listen       80;
    server_name  testlua.com;
    index index.html index.htm index.php;
    root  /data0/htdocs/www;
    location /hello {
            default_type 'text/plain';
            set $ua $http_user_agent;

            rewrite_by_lua '
                local memcached = require "resty.memcached"
                local memc, err = memcached:new()
                if not memc then
                    ngx.say("failed to instantiate memc: ", err)
                    ngx.exit(200)
                    return
                end
            memc:set_timeout(1000) -- 1 sec
            local ok, err = memc:connect("127.0.0.1",11111)
            if not ok then
                ngx.say("failed to connect: ", err)
                ngx.exit(200)
                return
            end   
            local res, flags, err = memc:get(ngx.var.ua)
            if err then
                ngx.say("failed to get dog: ", err)
                ngx.exit(403)
                return 
            end
            if res then
                local cjson = require "cjson"
                result = cjson.decode(res)
                ngx.say(result.a)
                ngx.say(result.b)
                ngx.exit(200)
                return
            else
                ngx.say("The Value is empty.")
                ngx.exit(200)
                return
            end
            memc:close()
        '; 
   }
 }        

除非注明,本博客文章均为原创,转载请以链接形式标明本文地址
本文地址: http://blog.cnwyhx.com/nginx-lua-memcache/

Leave a Reply