lua使用zlib压缩和解压,luazlib解压


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

有两种方式可以完成

第一种:使用lua-zlib

看了一下别人的方式,http://blog.csdn.net/kowity/article/details/7229815;

在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, output, 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。代码很简单,压缩一个字符串和解压一个字符串!


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









相关内容

    暂无相关文章