Openresty本身也支持开辟内存添加共享缓存的空间,操作api与redis一致

本地缓存的作用

减少查询redis、mysql的操作,实际redis也很快,但是毕竟有网络开销。本地缓存会更快一些!

正文

nginx.conf配置文件http块下添加一个

lua_shared_dict mycache 128m;

配置文件如下

worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {

    # 加载lua模块
    lua_package_path "/usr/local/openresty/lualib/?.lua;;";
    # 加载c模块
    lua_package_cpath "/usr/local/openresty/lualib/?.so;;";
    # ① 开启本地共享缓存,会占用内存:150mb 缓存名mycache,自定义 
    lua_shared_dict mycache 128m;
    

    # 在这里配置,这样当前http块内需要用到cjson模块时,都不需要独自加载了
    init_by_lua_block{
        -- 注意,这里面是lua语法,注释是两个杠 不是井号
        cjson=require 'cjson';
        -- mysql=require("resty.mysql");
        -- redis=require 'resty.redis';
    }

    upstream diyServer{   # ban _ tomcat not spuuort
        hash $request_uri; # 让每个请求/item/id=001 访问到固定server,这样可以实现固定url去找固定server。(这样我Aserver的缓存,就不会请求Bserver了)
        server 192.168.31.204:8080;        # ①  自己springboot写一个请求返回(证明openresty发送了http请求)
        keepalive 50;               # ② 一定要添加keepalive保持长链接,减少连接导致的性能损失
        # 一个长连接处理最大请求数(定期释放内存,防止内存溢出)
        keepalive_requests 8192;
    }

    server {
        listen 9000;
        location / {
            default_type text/html;
            content_by_lua '
                ngx.say("<p>Hello, World! second test!</p>")
            ';
        }
        location /abc {
            lua_code_cache off;
            # default_type text/html;
            default_type application/json;
            content_by_lua_file lua/a.lua;
        }
        location /useForOtherUrlRequest{
            internal; # 只允许被内部访问,外部访问就是404
            proxy_pass http://diyServer/user/api/v1/hello/;
        }
    }
}

编写a.lua

-- 获取缓存对象 使用方法时 ngx.share.XXX
local getCache = ngx.shared.mycache;
-- 读取数据
local name = getCache:get('name')
ngx.say('第一次读取本地缓存!',name)
-- 添加数据 key,value,timeout(秒)
getCache:set('name','zhangsan',100)
getCache:set('name','zhangsan',10) -- 同key会被覆盖!也就是超时时间变为10秒了
-- getCache:set('name','zhangsan') -- 同key会被覆盖!也就是不会超时
ngx.say('缓存设定成功!')
-- 读取数据
local name = getCache:get('name')
ngx.say('第二次读取本地缓存!',name)
-- 删除数据
--getCache:delete('name')

-- 特别说明
-- 1、重载配置文件,缓存不会消失
-- 2、nginx重启才会删除缓存数据
特殊说明:
上述文章均是作者实际操作后产出。烦请各位,请勿直接盗用!转载记得标注原文链接:www.zanglikun.com
第三方平台不会及时更新本文最新内容。如果发现本文资料不全,可访问本人的Java博客搜索:标题关键字。以获取全部资料 ❤