LMLPHP后院

OpenResty Lua Redis 加速接口响应技术

maybe yes 发表于 2017-09-19 10:41

本文以完整的示例,展示使用 Nginx、Lua、Redis 对响应速度慢的接口进行加速响应,提供快速的用户体验。代码经过严格的测试,没有任何问题。缓存的核心思想在于读取缓存后,即时中断连接,返回结果,然后继续执行,更新缓存。可以缓存的接口一般都是与用户无关的接口,比如计算当日热度最高的商品排行等。

需要加速的接口代码,如下示例:

<?php
sleep(2);
echo 'sleep 2 seconds, date is '.date("Y-m-d H:i:s")."\n";

测试接口访问效果,需要等待 2 秒后才能返回结果,如下示例:

$ curl -XGET lua.may:90/test.php
sleep 2 seconds, date is 2017-09-19 10:44:58

以下代码的核心作用就是使用 Lua 对接口内容进行操作存储到 redis 中;一旦有请求过来,立即读取缓存,快速响应,然后再去更新缓存,使用 ngx.eof() 实现非阻塞。下面的例子中使用了 content_by_lua,实际使用时,可以使用 content_by_lua_file 进行封装。OpenResty Nginx 配置如下:

server {
    listen 90;
    server_name lua.may;
    error_log /usr/local/openresty/log/nginx/lua.may.error.log;
    charset utf-8;
    root /srv/www/may/lua;
    index index.html index.php;
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    location ~ \.php$ {
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_split_path_info ^(.+\.php)(.*)$;
        include fastcgi_params;
    }

    location /accelerate_test {
        content_by_lua '
            local redis = require "resty.redis"
            local cache = redis.new()
            cache.connect(cache, "127.0.0.1", "6379")
            cache:auth("password");
            local cache_content = cache:get("foo")
            if cache_content==ngx.null then
                local res = ngx.location.capture("/test.php")
                ngx.say("data: " .. res.body)
                cache:set("foo", res.body)
                return
            end
            ngx.say("cache: " .. cache_content)
            ngx.eof();

            local res = ngx.location.capture("/test.php")
            cache:set("foo", res.body)
        ';
    }
}

使用加速接口后,即时返回结果,没有任何延迟:

$ curl -XGET lua.may:90/accelerate_test
cache: sleep 2 seconds, date is 2017-09-19 10:45:40

以上就是完整的示例,技术本身都是很简单的,难就难在代码实现上。

相关文章
2024-04-27 06:17:04 1714169823 0.032387