加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

lua使用zlib压缩和解压

发布时间:2020-12-14 21:54:21 所属栏目:大数据 来源:网络整理
导读:最近学习lua+nginx。在项目中要使用nginx的反向代理,从中遇见诸多麻烦!最蛋疼的是使用的平台是windows,哎!这套东西在window的相关文档资料很少!写写关于lua使用zlib压缩和解压的问题。 有两种方式可以完成 第一种:使用lua-zlib 看了一下别人的方式,ht

最近学习lua+nginx。在项目中要使用nginx的反向代理,从中遇见诸多麻烦!最蛋疼的是使用的平台是windows,哎!这套东西在window的相关文档资料很少!写写关于lua使用zlib压缩和解压的问题。

有两种方式可以完成

第一种:使用lua-zlib

看了一下别人的方式,http://www.voidcn.com/article/p-gbnhgugs-bmk.html;

在windows下编译这几个库并没成功,失败了。

第二种:使用lua-ffi-zlib。

使用之前必须有zlib包,如果使用的是openresty,在跟目录下回有.so或者dll库文件。PS:下载之后文件中的名字是zlib.dll,更改为zlib1.dll

下载文件https://github.com/hamishforbes/lua-ffi-zlib,里面有测试用例。可以直接使用!

if arg[1] == nil then
    print("No file provided")
    return
else
    f = io.open(arg[1],"rb")
    input = function(bufsize)
        local d = f:read(bufsize)
        if d == nil then
            return nil
        end
        in_crc = zlib.crc(d,in_crc)
        in_adler = zlib.adler(d,in_adler)
        uncompressed = uncompressed..d
        return d
    end
end

PS:注意这段代码,这里input函数结束的标准是返回nil,如果返回其他的会报错或者死循环。

修改之后的我的版本:


local table_insert = table.insert
local table_concat = table.concat
local zlib = require('ffi-zlib')
local chunk = 16384

local str = "ab"
local count = 0
local input = function(bufsize)
	local start = count > 0 and bufsize*count or 1
    local data = str:sub(start,(bufsize*(count+1)-1))
	if data == "" then
		data = nil
	end
	ngx.say("##################")
	ngx.say(data)
	ngx.say("##################")
    count = count + 1
    return data
end


local output_table = {}
local output = function(data)
    table_insert(output_table,data)
end

-- Compress the data
ngx.say('Compressing')
local ok,err = zlib.deflateGzip(input,output,chunk)
if not ok then
    ngx.say(err)
end
local compressed = table_concat(output_table,'')
ngx.say("---------------------------")
ngx.say(compressed)
ngx.say("---------------------------")


-- Decompress it again

ngx.say('Decompressing')
output_table = {}
local count = 0
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 ok,err = zlib.inflateGzip(input,chunk)
if not ok then
    ngx.say(err)
end
local output_data = table_concat(output_table,'')

ngx.say("---------------------------")
ngx.say(output_data)
ngx.say("---------------------------")


如果没有使用nginx,ngx.say换位print。代码很简单,压缩一个字符串和解压一个字符串!


有更好的方法,请大家赐教!谢谢

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读