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

标签 java redis binary jedis

我正在尝试向/从 Redis 写入和读取 gzip。问题是我尝试将读取的字节保存到一个文件中并使用 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());

关于java - Redis/java - 写入和读取二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41245658/

相关文章:

python - Redis - Amazon EC2 上的 Celery 配置

javascript - JS : Why is ~10 (binary, ~1010) = -11 (二进制, -1011)?

vba - 读取 Excel 文件的 VBA 宏(或 vbaProject.bin),而无需在 MS Excel 中打开它

写入字节数组时出现java.lang.NullPointerException

java - 静态字段的 JUnit 初始化

java - 在 mac osx mavericks 上设置 eclipse 时出现问题

c# - 使用 Redis、key 或 Id 存储对象标识符?

java - 在 Android 中使用 AES/GCM/NoPadding 加密的消息解密时出错

spring-boot - 中型数据项目需要选择哪个分布式数据库

c - 给定一个字节,从二进制中确定一个特定值