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正则

相关推荐
Narutolxy5 天前
使用 OpenResty 构建高效的动态图片水印代理服务20250127
junit·openresty
龙哥·三年风水10 天前
openresty(nginx)+lua+kafka实现日志搜集系统
kafka·lua·openresty
請叫我菜鳥17 天前
什么是 OpenResty
nginx·lua·openresty
Hello.Reader21 天前
深入浅出 OpenResty
junit·openresty
山人在山上1 个月前
nginx(openresty) lua 解决对接其他平台,响应文件中地址跨域问题
nginx·lua·openresty
码农小伙1 个月前
OpenResty开发环境搭建
openresty
云海04781 个月前
OpenResty、Lua介绍认识
junit·lua·openresty
努力--坚持1 个月前
电商项目-网站首页高可用(一)
nginx·lua·openresty
m0_748250741 个月前
高性能Web网关:OpenResty 基础讲解
前端·openresty
大熊程序猿1 个月前
docker 安装openresty
docker·容器·openresty