Redis/java - 写入和读取二进制数据

Redis/java - writing and reading binary data

我正在尝试写入和读取 gzip to/from Redis。问题是我尝试将读取的字节保存到一个文件中并使用 gzip 打开它——它是无效的。在 Eclipse 控制台中查看时,字符串也不同。

这是我的代码:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import redis.clients.jedis.Jedis;

public class TestRedis
{

  public static void main(String[] args) throws IOException
  {
    String fileName = "D:/temp/test_write.gz";

    String jsonKey = fileName;

    Jedis jedis = new Jedis("127.0.0.1");

    byte[] jsonContent = ReadFile(new File(fileName).getPath());

    // test-write data we're storing in redis
    FileOutputStream fostream = new FileOutputStream("D:/temp/test_write_before_redis.gz"); // looks ok
    fostream.write(jsonContent);
    fostream.close();

    jedis.set(jsonKey.getBytes(), jsonContent);

    System.out.println("writing, key: " + jsonKey + ",\nvalue: " + new String(jsonContent)); // looks ok

    byte[] readJsonContent = jedis.get(jsonKey).getBytes();
    String readJsonContentString = new String(readJsonContent);
    FileOutputStream fos = new FileOutputStream("D:/temp/test_read.gz"); // invalid gz file :( 
    fos.write(readJsonContent);
    fos.close();

    System.out.println("n\nread json content from redis: " + readJsonContentString);

  }

  private static byte[] ReadFile(String aFilePath) throws IOException
  {
    Path path = Paths.get(aFilePath);
    return Files.readAllBytes(path);
  }

}

您正在使用 Jedis.get(String) 阅读其中包括内部 UTF-8 转换。但是用Jedis.set(byte[], byte[])写不包括这样的转换。不匹配可能是因为这个原因。如果是这样,您可以尝试 Jedis.get(byte[]) 从 redis 读取以跳过 UTF-8 转换。例如

byte[] readJsonContent = jedis.get(jsonKey.getBytes());