用于发送到Sidekiq/Redis的Ruby ZIP文件编码

用于发送到Sidekiq/Redis的Ruby ZIP文件编码,ruby,encoding,redis,sidekiq,Ruby,Encoding,Redis,Sidekiq,我使用以下代码构建一个ZIP文件: def compress_batch(directory_path) zip_file_path = File.join( File.expand_path("..", directory_path), SecureRandom.hex(10)) Zip::File.open(zip_file_path, Zip::File::CREATE) do |zip_file| (Dir.entries(directory_path) - %w(. .

我使用以下代码构建一个ZIP文件:

def compress_batch(directory_path)
  zip_file_path = File.join( File.expand_path("..", directory_path), SecureRandom.hex(10))
  Zip::File.open(zip_file_path, Zip::File::CREATE) do |zip_file|
    (Dir.entries(directory_path) - %w(. ..)).each do |file_name|
      zip_file.add file_name, File.join(directory_path, file_name)
    end
  end

  result = File.open(zip_file_path, 'rb').read
  File.unlink(zip_file_path)
  result
end
我将该ZIP文件存储在内存中:

@result = Payoff::DataFeed::Compress::ZipCompress.new.compress_batch(source_path)
我把它放到一个散列中:

options = {
  data: @result
}
然后我使用
perform\u async
将其提交给我的SideKiq工作人员:

DeliveryWorker.perform_async(options)
并获取以下错误:

[DEBUG]   Starting store to: { "destination" => "sftp", "path" => "INBOUND/20191009.zip" }
Encoding::UndefinedConversionError: "\xBA" from ASCII-8BIT to UTF-8
from ruby/2.3.0/gems/activesupport-4.2.10/lib/active_support/core_ext/object/json.rb:34:in `encode'
但是,如果我使用
.new.perform
而不是
.perform\u async
,绕过SideKiq,它可以正常工作

DeliveryWorker.new.perform(options)

我最好的猜测是,我的编码有问题,当工作转到SideKiq/Redis时,它就崩溃了。我应该如何编码它?我是否需要更改ZIP文件的创建?也许我可以在提交到SideKiq时转换编码?

SideKiq将参数序列化为JSON。您正在尝试将二进制数据填充到JSON中,JSON只支持UTF-8字符串。如果希望通过Redis传递数据,则需要对数据进行Base64编码

require 'base64'

encoded = Base64.encode64(filedata)

Sidekiq将参数序列化为JSON。您正在尝试将二进制数据填充到JSON中,JSON只支持UTF-8字符串。如果希望通过Redis传递数据,则需要对数据进行Base64编码

require 'base64'

encoded = Base64.encode64(filedata)
当您执行
.new.perform
时,它会工作,因为没有任何东西会被序列化为JSON并推送到Redis——作业是直接调用的。当您执行
.new.perform
时,它会工作,因为没有任何东西会被序列化为JSON并推送到Redis——作业是直接调用的。