You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UnifiedJedis jsonSet写入大JSON数据堆内存占用过高求助

解决大文件JSON写入Redis的内存占用问题

问题原因

你的代码通过Files.readAllBytes一次性将63.4MB的文件加载到内存生成byte[],这个数组本身就占用约63MB内存。加上Jedis处理该数组时的内存开销(如数据复制、编码转换、传输缓冲区等),最终导致堆内存占用大幅膨胀至近500MB。

正确实现方式

采用流式传输的方式,避免一次性加载整个文件到内存,分块读取文件内容并直接发送给Redis,可大幅降低堆内存占用。

代码示例

public static void main(String[] args) {
    HostAndPort config = new HostAndPort("localhost", 6379);
    PooledConnectionProvider pooledConnectionProvider = new PooledConnectionProvider(config);
    try (UnifiedJedis jedisClient = new UnifiedJedis(pooledConnectionProvider, 10, Duration.ofSeconds(120));
         FileInputStream fis = new FileInputStream("C:\\tmp\\flowdata1.txt")) {
        
        String key = "exampleKey" + System.currentTimeMillis();
        // 通过底层BinaryClient流式发送JSON.SET命令
        jedisClient.getBinaryJedis().sendCommand(Command.JSON_SET, key, ".", fis);
        System.out.println("Data written to Redis successfully!");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

关键说明

  • 使用FileInputStream流式读取文件,每次仅加载小部分数据到内存,避免大数组占用堆空间。
  • 调用BinaryJedis.sendCommand方法,直接将输入流作为命令参数传递,Jedis会自动分块将数据发送至Redis,无需在内存中缓存完整文件内容。
  • 确保目标文件是合法的JSON格式,否则JSON.SET命令会执行失败。

内容的提问来源于stack exchange,提问作者Ganesh Gudghe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 14:40:02