如何解压缩在 ruby 中使用 gzip 压缩的节点数据?
How to decompress in node data that was compressed in ruby with gzip?
我们有一个 ruby 实例,它通过 rabbitmq(bunny 和 amqplib)向节点实例发送消息,如下所示:
{ :type => data, :data => msg }.to_bson.to_s
这似乎进展顺利,但消息有时很长,我们正在跨数据中心发送它们。 zlib 会有很大帮助。
在 ruby 发件人中这样做:
encoded_data = Zlib::Deflate.deflate(msg).force_encoding(msg.encoding)
然后在节点中读取它:
data = zlib.inflateSync(encoded_data)
returns
"\x9C" from ASCII-8BIT to UTF-8
我想做的事情可行吗?
我不是 Ruby 开发人员,所以我将或多或少用伪代码编写 Ruby 部分。
Ruby代码(运行在线https://repl.it/BoRD/0)
require 'json'
require 'zlib'
car = {:make => "bmw", :year => "2003"}
car_str = car.to_json
puts "car_str", car_str
car_byte = Zlib::Deflate.deflate(car_str)
# If you try to `puts car_byte`, it will crash with the following error:
# "\x9C" from ASCII-8BIT to UTF-8
#(repl):14:in `puts'
#(repl):14:in `puts'
#(repl):14:in `initialize'
car_str_dec = Zlib::Inflate.inflate(car_byte)
puts "car_str_dec", car_str_dec
# You can check that the decoded message is the same as the source.
# somehow send `car_byte`, the encoded bytes to RabbitMQ.
节点代码
var zlib = require('zlib');
// somehow get the message from RabbitMQ.
var data = '...';
zlib.inflate(data, function (err, buffer) {
if (err) {
// Handle the error.
} else {
// If source didn't have any encoding,
// no need to specify the encoding.
console.log(buffer.toString());
}
});
我还建议您坚持使用 Node 中的异步函数,而不是同步函数。
我们有一个 ruby 实例,它通过 rabbitmq(bunny 和 amqplib)向节点实例发送消息,如下所示:
{ :type => data, :data => msg }.to_bson.to_s
这似乎进展顺利,但消息有时很长,我们正在跨数据中心发送它们。 zlib 会有很大帮助。
在 ruby 发件人中这样做:
encoded_data = Zlib::Deflate.deflate(msg).force_encoding(msg.encoding)
然后在节点中读取它:
data = zlib.inflateSync(encoded_data)
returns
"\x9C" from ASCII-8BIT to UTF-8
我想做的事情可行吗?
我不是 Ruby 开发人员,所以我将或多或少用伪代码编写 Ruby 部分。
Ruby代码(运行在线https://repl.it/BoRD/0)
require 'json'
require 'zlib'
car = {:make => "bmw", :year => "2003"}
car_str = car.to_json
puts "car_str", car_str
car_byte = Zlib::Deflate.deflate(car_str)
# If you try to `puts car_byte`, it will crash with the following error:
# "\x9C" from ASCII-8BIT to UTF-8
#(repl):14:in `puts'
#(repl):14:in `puts'
#(repl):14:in `initialize'
car_str_dec = Zlib::Inflate.inflate(car_byte)
puts "car_str_dec", car_str_dec
# You can check that the decoded message is the same as the source.
# somehow send `car_byte`, the encoded bytes to RabbitMQ.
节点代码
var zlib = require('zlib');
// somehow get the message from RabbitMQ.
var data = '...';
zlib.inflate(data, function (err, buffer) {
if (err) {
// Handle the error.
} else {
// If source didn't have any encoding,
// no need to specify the encoding.
console.log(buffer.toString());
}
});
我还建议您坚持使用 Node 中的异步函数,而不是同步函数。