java - 在春季设置 GOOGLE_APPLICATION_CREDENTIALS
问题描述
我正在尝试使用 Spring 从 Google Storage Buckets 访问文件,最终目标是使用 MultiResourceItemReader 从存储桶中读取多个 XML 文件。当 XML 文件在我的机器上(不是 GCP)本地时,我目前让 Spring 处理这个过程
现在,我想做同样的事情,但不是我机器上的 XML 文件,而是 GCP 存储桶中的文件。我可以访问 Spring 之外的存储桶内容,一次一个文件。例如,这一点测试代码允许我访问存储桶,然后查看存储桶中的文件。在此代码段中,我通过 JSON 密钥文件设置凭据。(不是环境变量)
public static void storageDriver() throws IOException {
// Load credentials from JSON key file. If you can't set the GOOGLE_APPLICATION_CREDENTIALS
// environment variable, you can explicitly load the credentials file to construct the
// credentials.
String name = "";
String bucketName = "";
String bucketFileName = "";
String bucketFullPath = "";
Resource myBucker;
GoogleCredentials credentials;
File credentialsPath = new File("mycreds.json");
try (FileInputStream serviceAccountStream = new FileInputStream(credentialsPath)) {
credentials = ServiceAccountCredentials.fromStream(serviceAccountStream);
}
Storage storage = StorageOptions.newBuilder()
.setCredentials(credentials)
.setProjectId("myProject")
.build()
.getService();
for (Bucket bucket:storage.list().iterateAll()){
if(bucket.getName().equalsIgnoreCase("myGoogleBucket")){
bucketName = bucket.getName();
System.out.println(bucket);
for (Blob blob : bucket.list().iterateAll()){
bucketFileName = blob.getName();
bucketFullPath = "gs://"+bucketName+"/"+bucketFileName;
System.out.println(bucketFullPath);
}
}
};
但是,当我尝试使用 Spring 执行以下操作时,Spring 抱怨我没有GOOGLE_APPLICATION_CREDENTIALS
定义。(当然我不这样做,因为我是以编程方式进行的。
例如,我将添加
@Value("gs://myGoogleBucket")
private Resource[] resources;
应用程序默认凭据不可用。如果在 Google Compute Engine 中运行,它们就可用。GOOGLE_APPLICATION_CREDENTIALS
否则,必须定义环境变量以指向定义凭据的文件。
解决方案
Spring Cloud GCP 简化了您的 GCS 配置。
您可以将存储支持添加到您的应用程序。然后,通过spring.cloud.gcp.storage.credentials.location
属性指定服务帐户凭据的位置,或者使用 Google Cloud SDK 使用应用程序默认凭据登录。
这将自动为您提供一个完全配置的Storage
对象,并且@Value(gs://YOUR-BUCKET/YOUR-FILE)
应该可以正常工作。
推荐阅读
- dataframe - 我想在 Julia 中连接匿名电话
- ms-access-2016 - 显示空白列表的子表单未绑定组合框
- python - 从python中的值获取键并使用键而不是值来执行任何操作
- java - Android 媒体播放器版本不起作用
- excel - 将范围粘贴为图片时出现 Outlook 图像错误
- snowflake-cloud-data-platform - 使用传递的变量插入表雪花
- python - Python(几乎没问题):字符串拆分器
- c# - 函数只返回输入变量的第一个值
- java - InputStream 读取“合理”长度的文本,避免阻塞
- java - 如何从模型对象访问特定的字段列表