• 缓存预热加入二级缓存


    缓存预热加入二级缓存

    image-20201120001947011

    [root@localhost ~]# cat /root/lua/ad_read.lua
    --设置响应头类型
    ngx.header.content_type="application/json;charset=utf8"
    --获取请求中的参数ID
    local uri_args = ngx.req.get_uri_args();
    local user_id = uri_args["user_id"];
    
    --获取本地缓存
    local cache_ngx = ngx.shared.dis_cache;
    --根据ID 获取本地缓存数据
    local adCache = cache_ngx:get('id_cache_'..user_id);
     ngx.say(adCache)
    if adCache == "" or adCache == nil then
         --引入redis库
         local redis = require("resty.redis");
         --创建redis对象
         local red = redis:new()
         --设置超时时间
         red:set_timeout(2000)
         --连接
         red:connect("192.168.1.104", 6379)
         --获取key的值
         local rescontent=red:get("id_"..user_id)
         if ngx.null == rescontent  then
            local cjson = require("cjson")
            local mysql = require("resty.mysql")
            local db = mysql:new()
            db:set_timeout(1000)
    
       local props = {
        host = "192.168.1.104",
        port = 3306,
        database = "user_db",
        user = "root",
        password = "root"
       }
    
         local res = db:connect(props)
    
         local select_sql = "select * from t_user where  user_id="..user_id
         res = db:query(select_sql)
         local responsejson = cjson.encode(res)
         red:set("id_"..user_id,cjson.encode(res))
         ngx.say(responsejson)
         db:close()
    
        else
           cache_ngx:set('id_cache_'..user_id,rescontent,2*60);
           ngx.say(rescontent)
        end
         --关闭连接
         red:close()
    else
     --nginx本地缓存中获取到数据直接输出
     ngx.say(adCache)
    end
    [root@localhost ~]#
    
    

    设置nginx的缓存

    image-20201120012234418

    开始第一次请求,nginx缓存没有,redis没有,访问数据库,并存入redis中

    image-20201120011556066

    开始第二次请求,nginx缓存没有,redis有。开始存入nginx中

    image-20201120011609826

    开始第三次请求,nginx有缓存

    image-20201120011621768

  • 相关阅读:
    50.2 Django 连接MySQL,django orm 数据库(models)操作
    50.1 Django 静态资源配置 static && form表单和 request对象
    JS备忘
    Python 单元测试 生产HTML测试报告
    python 单元测试 执行测试
    pycharm 安装插件
    Python 单元测试 实战演练
    Python 单元测试
    Pycharm 使用备忘
    Python 异常
  • 原文地址:https://www.cnblogs.com/dalianpai/p/14008881.html
Copyright © 2020-2023  润新知