如何通过Java API结合服务账号密钥列出Dataproc集群?
Java实现Dataproc集群列表查询(服务账号认证)
1. 添加Maven依赖
首先确保项目引入Google Cloud Dataproc的Java客户端依赖:
<dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-dataproc</artifactId> <version>2.32.0</version> <!-- 建议使用最新稳定版本 --> </dependency>
2. 核心实现代码
通过服务账号JSON密钥完成认证,并调用Dataproc API获取集群列表:
import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.dataproc.v1.ClusterControllerClient; import com.google.cloud.dataproc.v1.ClusterControllerSettings; import com.google.cloud.dataproc.v1.Cluster; import com.google.protobuf.Empty; import java.io.FileInputStream; import java.io.IOException; public class DataprocClusterLister { public static void main(String[] args) throws IOException { // 替换为你的服务账号JSON密钥路径 String serviceAccountKeyPath = "/path/to/your/service-account-key.json"; // 替换为你的GCP项目ID和目标区域 String projectId = "your-gcp-project-id"; String region = "us-central1"; // 加载服务账号凭据 GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(serviceAccountKeyPath)) .createScoped("https://www.googleapis.com/auth/cloud-platform"); // 配置Dataproc客户端 ClusterControllerSettings clientSettings = ClusterControllerSettings.newBuilder() .setCredentialsProvider(() -> credentials) .setEndpoint(region + "-dataproc.googleapis.com:443") .build(); // 自动管理客户端资源 try (ClusterControllerClient client = ClusterControllerClient.create(clientSettings)) { String parentResource = String.format("projects/%s/regions/%s", projectId, region); // 遍历所有集群并输出关键信息 for (Cluster cluster : client.listClusters(parentResource, Empty.newBuilder().build()).iterateAll()) { System.out.printf("集群名称: %s%n状态: %s%n创建时间: %s%n---%n", cluster.getClusterName(), cluster.getStatus().getState(), cluster.getStatus().getStateStartTime()); } } } }
关键注意点
- 端点配置:Dataproc客户端需要指定区域对应的端点,格式为
{region}-dataproc.googleapis.com:443,需根据实际使用的区域调整 - 权限要求:确保服务账号拥有
roles/dataproc.viewer或更高权限(如roles/dataproc.editor),否则会返回权限不足错误 - 资源管理:使用
try-with-resources模式自动关闭客户端,避免资源泄漏
内容的提问来源于stack exchange,提问作者QueryQuasar
相关产品推荐
相关产品推荐

