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

相关推荐
爱编码的钓鱼佬5 天前
浅谈openresty
运维·nginx·openresty
shall_zhao6 天前
安装OpenResty(Linux-Docker)
linux·docker·openresty
shall_zhao8 天前
黑马点评18——多级缓存-OpenResty
redis·缓存·lua·openresty
代码是谁9 天前
centos8构建nginx1.27.1+BoringSSL+http3+lua+openresty
nginx·lua·http3·openresty
刘大帅ps1 个月前
高性能 Web 服务器:让网页瞬间绽放的魔法引擎(下)
linux·运维·服务器·网络·nginx·负载均衡·openresty
ciqingloveless1 个月前
openresty整合modsecurity实现简单的防止DDOS攻击
ddos·openresty
Roc-xb2 个月前
Docker安装 OpenResty详细教程
docker·容器·openresty
秃了也弱了。2 个月前
OpenResty使用Lua笔记
lua·openresty
菜就多练_08282 个月前
《0基础》学习Python——第十一讲__时间函数
开发语言·python·学习·pycharm·时间函数
路多辛2 个月前
OpenResty程序如何连接开启了TLS的Redis?
数据库·redis·openresty