Nginx+Lua+redis, 商品详情页缓存技术

需要使用openresty软件

1  lua配置

    test.lua 需要写入缓存逻辑

\#user  nobody;  
worker_processes  2;  
error_log  logs/error.log;  
events {  
    worker_connections  1024;  
}  
http {  
    include       mime.types;  
    default_type  text/html;  

    #lua模块路径,其中”;;”表示默认搜索路径,默认到/usr/servers/nginx下找  
    lua_package_path "/usr/example/lualib/?.lua;;";  #lua 模块  
    lua_package_cpath "/usr/example/lualib/?.so;;";  #c模块  
    
    server {  
        listen       80;  
        server_name  _;  

        location /lua {  
            default_type 'text/html';  
            lua_code_cache off;  
            content_by_lua_file /usr/example/lua/test.lua;  
        }  
    }    
}   

2  test.lua 中缓存代码

    a)业务内容:会将商品id请求参数

    b)处理过程:

             1、应用nginx的lua脚本接收到请求

              2、获取请求参数中的商品id

              3、根据商品id,在nginx本地缓存中尝试获取数据

              4、如果在nginx本地缓存中没有获取到数据,那么就到redis分布式缓存中获取数据,如果获取到了数据,还要设置到nginx本地缓存中但是这里有个问题,

              建议不要用nginx+lua直接去获取redis数据因为openresty没有太好的redis cluster的支持包,所以建议是发送http请求到缓存数据生产服务,由该服务提供一个http接口缓存数生产服务可以基于redis cluster api从redis中直接获取数据,并返回给nginx

      c) test.lua 代码 

--读取get参数
local uri_args = ngx.req.get_uri_args()
--读取post参数
--ngx.req.read_body()
--local uri_args = ngx.req.get_post_args()

local productId = uri_args["productId"] 
local cache_ngx = ngx.shared.my_cachelocal 
productCacheKey = "product_info_"..productIdlocal 
productCache = cache_ngx:get(productCacheKey)
if productCache == "" or productCache == nil then    
   /**
   local http = require("resty.http")    
   local httpc = http.new()    
   local resp, err = httpc:request_uri("http://192.168.31.179:8080",
        {          
            method = "GET",          
            path = "/getProductInfo?productId="..productId    
        })    
    productCache = resp.body 
    httpc:close()    
    **/

    //访问redis方式
    local redis = require "resty.redis"
    local red = redis:new()
    red:set_timeout(1000) -- 1 sec
    local ok, err = red:connect("127.0.0.1", 6379)

    --set
    --local res, err = red:set(key, value)

    --get
    local productCache, err = red:get(key)
    red:close()

    cache_ngx:set(productCacheKey, productCache, 10 * 60)
end

ngx.say(productCache)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值