java openresty 调用_Openresty使用zlib解压缩response body

产品需要对当前的所有接口进行统计数据,其中需要边缘层返回需要用到的response body的状态码以及信息

概述

目前后台返回的response body既有压缩又有不压缩,所以导致处理数据需要进行分支处理,否则会导致无法访问,大概思路就是在你的openresty中下的配置文件增加一个处理response body的字段body_filter_by_lua_file,然后在该入口内处理你的逻辑,在这里我这的大概逻辑是解码,解压缩,处理异常,然后把数据写到日志

处理流程

在配置文件你要处理的server中添加

#conf/lua/get_resp.lua:相对路径下的lua处理文件

body_filter_by_lua_file conf/lua/get_resp.lua;

# 设置日志变量

set $resp_code '';

set $resp_msg '';

下载zlib库 点我下载

wget https://github.com/hamishforbes/lua-ffi-zlib

编写逻辑代码

local json = require "cjson"

local zlib = require 'ffi-zlib'

``

function json_decode(str)

local data = nil

_, err = pcall(function(str) return json.decode(str) end, str)

return data, err

end

local chunk = string.sub(ngx.arg[1], 1, 1000)

ngx.ctx.buffered = (ngx.ctx.buffered or "") .. chunk

if ngx.arg[2] then

--ngx.ctx.buffered获取到response body的压缩数据 compressed = ngx.ctx.buffered

output_table = {}

local chk = 16384

local input = function(bufsize)

local start = count > 0 and bufsize*count or 1

local data = compressed:sub(start, (bufsize* (count+1)-1))

count = count + 1

return data

end

local output = function(data)

table_insert(output_table, data)

end

local ok, err = zlib.inflateGzip(input, output, chk)

if not ok then

ngx.log(ngx.ERR,'decompress err:'..err)

return

end

local output_data = table_concat(output_table,'')

--ngx.log(ngx.ERR,'decompress res:'..output_data)

local err,data = json_decode(output_data)

if err then

ngx.log(ngx.ERR,'compress decode err:'..err)

end

-- data就是需要的table数据

-- 这里也需要做异常判断,你自己加就好了

ngx.var.resp_code = data['code']

ngx.var.resp_msg = data['msg']

end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值