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

相关推荐
杨了个杨89825 天前
Tengine与OpenResty
openresty
曹天骄5 天前
OpenResty 源站安全隔离设计在边缘计算架构中的工程实践
安全·边缘计算·openresty
快乐肚皮10 天前
OpenResty:Nginx的进化之路
nginx·junit·openresty
landonVM12 天前
OpenResty 的性能优化配置建议
性能优化·openresty
我发在否21 天前
OpenResty > Lua断点调试
vscode·lua·断点·openresty·luapanda
oMcLin1 个月前
如何在 CentOS 7 上通过配置和调优 OpenResty,提升高并发 Web 应用的 API 请求处理能力?
前端·centos·openresty
笑笑�1 个月前
OpenResty + nginx_upstream_check_module 构建主动健康检查模块
运维·nginx·负载均衡·openresty
Wang's Blog1 个月前
Lua: Web应用开发之OpenResty与Lapis框架深度指南
lua·openresty
驯龙高手_追风1 个月前
OpenResty+NtripCaster实现挂载点负载均衡使用初探
junit·负载均衡·openresty
秃了也弱了。1 个月前
OpenResty+redis实现基于ip的代理层灰度发布
redis·tcp/ip·openresty