API(十)时间相关的SDK

一 时间相关的SDK

① 时间记录的必要性

bash 复制代码
1、'案发'现场的时间点

2、通过时间判断'性能'

3、时间的'不准确'性,日志'落盘'时间   --> '缓冲区'导致延迟

② 使用哪些日期和时间的函数

bash 复制代码
1、lua 标准'时间'函数,函数 'os.time'、'os.date' 和 'os.difftime' 提供了所有日期和时间

2、在 openresty 的世界里,'不推荐'使用这里的标准时间函数

3、原因:标准函数通常会引发不止一个昂贵的'系统调用',同时无法进行LuaJIT 编译,对性能影响较大

4、推荐使用 'ngx_lua 模块'提供的'带缓存'的时间接口,API'如下':

ngx.say('ngx.time()' .. ngx.time())
ngx.say('ngx.now()' .. ngx.now())
ngx.say('ngx.today()' .. ngx.today())
ngx.say('ngx.localtime()' .. ngx.localtime())
ngx.say('ngx.utctime()' .. ngx.utctime())
ngx.say('ngx.cookie_time(1500456075)' .. ngx.cookie_time(1500456075))
ngx.say('ngx.http_time(1500456075)' .. ngx.http_time(1500456075))
ngx.say('os.time()' .. os.time())
ngx.say('------')
ngx.say(ngx.update_time())

lua标准时间函数

ngx.req.start_time

③ 时间类的SDK

ngx.today

bash 复制代码
时间戳: 获取'当前的时间戳'可以使用'如下'两个函数
​
1、在'实践'中我们通常使用'ngx.now'获取更'精确 [毫秒级别]'的时间用来计时

2、想要获取'更高的精确度'需要通过'ffi库'调用系统函数gettimeofday()

ngx.time

ngx.now

bash 复制代码
1、ngx.localtime、ngx.time、ngx.now等函数获取的时间基于OpenResty'内部缓存'的时间

备注: 与实际时间相比可能存在'微小'的误差

需求: 如果想要随时获得'准确的时间'可以先调用函数'ngx.update_time',然后再'调用'时间函数

ngx.update_time()    -- 强制'更新'内部缓存的时间

ngx.update_time会使用'系统函数gettimeofday()'强制更新时间,成本较高,除非必要应当尽量少用

ngx.localtime

ngx.update_time

ngx.utctime

bash 复制代码
时间戳和字符串格式的时间可以'互相'转换,OpenResty 提供'如下'三个函数:

ngx.cookie_time

ngx.http_time

ngx.parse_http_time

④ 案例讲解

bash 复制代码
ngx.say'同'ngx.print,但是会最后输出一个'换行'符

ngx.sleep

bash 复制代码
同步'非阻塞'机制的解读:

1、ngx.sleep可以'睡眠'任意的时间长度

2、但'不会阻塞'整个服,这时OpenResty会基于协程机制转而'处理其他'的请求

3、等睡眠时间到再'回头'继续执行ngx.sleep后续的代码

注:不能在init_*、set_by_lua/header、body_ filter_by_lua/log_by_lua等阶段里'调用'

⑥ 其它参考

openresty的日志处理

Openresty踩坑日志 -- 阻塞问题

*_by_lua_block {} 正则的转义

bash 复制代码
ngx.timer.every 新技能: 定时扫描'本地文件'是否有变动,发现特定文件,则执行'shell'脚本

ngx.timer.at    启动一次任务,执行'crontab'定时任务,脱离'openresty'的管理

OpenResty、Lapis、Luarocks、OpenSSL全面升级

lua文章汇总

正确的记录日志

perlre正则

相关推荐
Clownseven6 天前
Nginx Lua模块(OpenResty)实战:动态化、智能化你的Nginx,实现复杂Web逻辑 (2025)
nginx·lua·openresty
龙哥·三年风水10 天前
openresty+lua+redis把非正常访问的域名加入黑名单
redis·lua·openresty
大得36914 天前
安装openresty使用nginx+lua,openresty使用jwt解密
nginx·lua·openresty
莱茵不哈哈21 天前
OpenResty 深度解析:构建高性能 Web 服务的终极方案
nginx·lua·kong·openresty·conf
万山y25 天前
OpenResty反向代理
openresty
古月的三个锦囊1 个月前
Nginx openresty web服务 与 Go 原生web服务性能对比
nginx·go·openresty
Julian.zhou2 个月前
MCP服务:五分钟实现微服务治理革命,无缝整合Nacos/Zookeeper/OpenResty
人工智能·微服务·zookeeper·交互·openresty
PatrickYao04222 个月前
雨云云应用测评!内测持续进行中!
mysql·部署·网站搭建·openresty·rca
ZZDICT2 个月前
OpenResty(Lua)+Redis实现动态封禁IP
redis·nginx·lua·openresty
衣舞晨风3 个月前
Apache APISIX 架构浅析
架构·apache·openresty·apisix