zhaodaoqin

  • Oct 13, 2022
  • Joined Oct 13, 2022
  • 如果有技术专家/前辈之前解决过这种需求,希望不吝指点::::

    • 一个需求:广告数据存在Redis中,它是有时效性的,当Redis中数据失效时,怎么能让本地缓存中的数据同步失效呢
      下面是lua脚本
      ngx.header.content_type="application/json;charset=utf8"
      -- 获取路径上的请求参数,数据类型类似于“map”
      local uri_args = ngx.req.get_uri_args();
      -- 获取ID参数
      local id = uri_args["id"];
      -- 声明变量接收Nginx配置文件中定义的共享缓存
      local cache_ngx = ngx.shared.dis_cache;
      -- 根据key获取本地缓存中的数据
      local contentCache = cache_ngx:get('content_cache_'..id);

      -- 本地缓存中没有查询到的处理逻辑
      if contentCache == "" or contentCache == nil then
      -- 引入 redis 模块
      local redis = require("resty.redis");
      local red = redis:new()
      -- 发起 redis 连接
      red:set_timeout(2000)


      -- 建立连接
      local host = "192.168.23.128";
      local port = 6379;
      local password = "000415";
      red:connect(host, port);
      red:auth(password);
      -- 获取数据
      local rescontent=red:get("content_"..id);
      -- 从redis中没有获取到数据的逻辑处理
      if ngx.null == rescontent then
          -- 引入cjson、mysql模块
          local cjson = require("cjson");
          local mysql = require("resty.mysql");
          -- 发起mysql连接
          local db = mysql:new();
          db:set_timeout(2000)
          local mysql_props = {
              host = "192.168.23.128",
              port = 3306,
              database = "cg_business",
              user = "root",
              password = "root"
          }
          local res = db:connect(mysql_props);
          -- 查询数据
          local select_sql = "select url,name,position from tb_content where status ='1' and id="..id;
          -- 解决数据库中文乱码问题
          db:query("SET NAMES utf8")
          res = db:query(select_sql);
          -- 编码
          local responsejson = cjson.encode(res);
          -- 放入Redis并设置生命周期,注意与本地缓存周期一致
          red:set("content_"..id,responsejson);
      	red:expire("content_"..id, 10 * 60);
          -- 响应数据
          ngx.say(responsejson);
          -- 关闭数据库连接
          db:close();
      else
          -- 从Redis中查询到数据后放入本地缓存
          cache_ngx:set('content_cache_'..id, rescontent, 10*60);
          -- 响应数据
          ngx.say(rescontent);
      end
      red:close();

      else
      ngx.say(contentCache);
      end