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

如何通过Java API获取Google Cloud Storage(GCS)的磁盘使用信息

GCS Java API实现类df存储用量统计最优方案

无需递归遍历存储桶对象,直接调用Google Cloud Monitoring的Java API读取GCS预聚合的存储用量指标即可实现,指标由GCS后台自动统计上报,无需自行计算。

核心说明

  • 用到的预聚合指标:storage.googleapis.com/storage/total_bytes,该指标会按存储桶、存储类别维度自动聚合桶内所有对象的总占用字节数,数据更新延迟约为1~2小时,满足绝大多数非实时的用量统计场景
  • 仅当你需要按前缀统计子目录的用量时,才需要调用storage.objects.list接口按前缀遍历聚合,全桶总量统计无需遍历

Java实现步骤

1. 引入依赖(Maven示例)

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-monitoring</artifactId>
  <version>3.29.0</version>
</dependency>

2. 代码示例

import com.google.cloud.monitoring.v3.MetricServiceClient;
import com.google.monitoring.v3.ListTimeSeriesRequest;
import com.google.monitoring.v3.Point;
import com.google.monitoring.v3.ProjectName;
import com.google.monitoring.v3.TimeInterval;
import com.google.protobuf.util.Timestamps;
import java.util.concurrent.TimeUnit;

public class GcsStorageUsageStats {
    public static long getBucketTotalUsage(String projectId, String bucketName) throws Exception {
        try (MetricServiceClient metricServiceClient = MetricServiceClient.create()) {
            ProjectName projectName = ProjectName.of(projectId);
            // 构造查询时间区间,取最近24小时的数据确保能拿到最新上报值
            TimeInterval interval = TimeInterval.newBuilder()
                .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
                .setStartTime(Timestamps.fromMillis(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)))
                .build();
            // 构造指标过滤条件,指定GCS桶和用量指标
            String filter = String.format(
                "metric.type=\"storage.googleapis.com/storage/total_bytes\" AND resource.labels.bucket_name=\"%s\"",
                bucketName
            );
            ListTimeSeriesRequest request = ListTimeSeriesRequest.newBuilder()
                .setName(projectName.toString())
                .setFilter(filter)
                .setInterval(interval)
                .setView(ListTimeSeriesRequest.TimeSeriesView.FULL)
                .build();
            // 遍历结果取最新的指标值
            for (var ts : metricServiceClient.listTimeSeries(request).iterateAll()) {
                if (!ts.getPointsList().isEmpty()) {
                    Point latestPoint = ts.getPoints(0);
                    return latestPoint.getValue().getInt64Value();
                }
            }
            return 0L;
        }
    }

    public static void main(String[] args) throws Exception {
        // 替换为你的项目ID和桶名
        long totalBytes = getBucketTotalUsage("your-project-id", "your-bucket-name");
        long usedKB = totalBytes / 1024;
        System.out.printf("存储桶总用量:%d KB (%.2f GB)%n", usedKB, usedKB / 1024.0 / 1024.0);
        // 可自行扩展展示逻辑对齐df命令的输出格式
    }
}

注意事项

  • GCS为对象存储,默认无固定存储容量上限,若需对齐df命令的可用容量、使用率字段,需先为存储桶配置存储配额,再额外拉取storage.googleapis.com/quota/total_bytes指标获取配额值,自行计算剩余容量和使用率
  • 权限要求:运行代码的服务账号需要具备roles/monitoring.viewer(或自定义包含monitoring.timeSeries.list权限的角色),同时具备对应存储桶的读取权限
  • 如果需要实时的精确到秒的存储用量数据,只能通过遍历桶内对象统计,没有其他更优方案
  • 该指标统计的是所有对象的实际存储字节数,包含多版本对象、未完成的分片上传等占用的空间,和gsutil du命令默认统计的结果一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:45:04