OpenResty之共享内存的使用

本文介绍如何在Nginx中配置100MB的共享内存,并演示了通过Lua脚本设置、获取和查询共享内存容量的具体方法。此外,还介绍了ngx_lua提供的安全API接口,如get_stale(), safe_set(), safe_add()等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、定义共享内存100MB,nginx.conf配置文件http域增加如下指令代码:

 http {
     lua_shared_dict share_mem_cache 100m;
     ...
 }

2、使用共享内存:

    location /set {
        content_by_lua_block {
        local share_mem_cache  = ngx.shared.share_mem_cache
        share_mem_cache:set("name", "xiaoming") 
        ngx.say("STORED")
        }   
    }   

    location /get {
        content_by_lua_block {
        local share_mem_cache  = ngx.shared.share_mem_cache
        ngx.say(share_mem_cache:get("name"))
        }   
    } 

    location /capacity {
        content_by_lua_block {
            require "resty.core.shdict"
            local share_mem_cache  = ngx.shared.share_mem_cache
            ngx.say(share_mem_cache:capacity())
        }   
    }

3、另外,ngx_lua还提供很多相对安全的api接口操作共享内存。

  • get_stale()
  • safe_set()
  • safe_add()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值