Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

openresty 使用心得 #55

Open
iliuyt opened this issue Apr 3, 2020 · 0 comments
Open

openresty 使用心得 #55

iliuyt opened this issue Apr 3, 2020 · 0 comments

Comments

@iliuyt
Copy link
Owner

iliuyt commented Apr 3, 2020

openresty

openresty 是nginx的plus版,openresty有很多插件可供用户直接使用,openresty提供可lua语言可进行开发。
openresty我的理解是一个强大的中间件,通常做网关使用,用于处理授权,负载均衡,熔断,限流,分流等网关职责。
将业务里非业务核心的内容抽离,让业务开发更专注业务本身。

kong

kong是基于openresty的网关项目,实现了各种网关的需求

lor

lor是一个lor框架,采用了nodejs的express风格,使用nodejs的人看这个框架会非常贴切,
如果需要,完全可以使用lor框架实现业务。这样就避免了nginx到后端的网络请求,直接将业务在nginx层做掉,
当然这个要看需求,不是所有的业务都是适合在nginx层做掉。

lua

一些简单的需求,可以直接通过lua脚本实现,openresty提供了连接mysql redis等数据库的库,方便我们实现
各种特殊的需求

我使用openresty做了什么

因为我们已经有一套现成的nodejs实现的网关项目,所以不需要kong这类再去重复开发,我们遇到的问题是一些静态文件和上传下载等类似非接口的流量经过网关,使得网关压力较大,但是目前我们的网关主要职责是对请求进行各层面的校验,但并不需要对内容进行处理。因此我们采用openresty在请求到来时进行判断是否为静态文件,如果是静态文件放过,然后在判断是否经过认证且认证未失效,如果未认证或失效,调用网关进行认证,如果认证通过,转发请求到后端服务器,否则返回网关错误内容。这样使得网关大大减少了压力,同时接入服务也可以更快的访问。

openresty 实战

AB test

  • 例如,根据redis判断是否存在ip来转发流量

黑名单

  • 静态黑名单,无需redis
  • 动态黑名单1,redis查询黑名单
  • 根据共享内存查询,定期同步redis,避免反复查询redis影响性能

限流

性能

  • ngx.var的性能和ngx.ctx查一个数量级
  • string var和string byte 性能查一个数量级
  • string.find < ngx.re.find 性能差一个数量级
  • 共享内存碾压redis,同时也很稳定,尽量使用共享内存
  • os.execute 会导致当前进程阻塞,但是新版本引用了nginx pac,老版本使用lua-resty-exec
  • ngx.timer 会导致内存泄漏,能尽早关闭就关闭

关于时间戳获取

  • ngx.time(), os.time(), ngx.now()
  • ngx.time 和 os.time 为秒级,ngx.now为毫秒级
  • os.time 涉及系统调用,ngx.time不会,所以ngx.time性能高于os.time
  • ngx.time 和 ngx.now 会缓存时间,如果需要刷新需要调用ngx.update_time()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant