首页 > 解决方案 > 在春季设置 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否则,必须定义环境变量以指向定义凭据的文件。

标签: javaspringgoogle-cloud-storage

解决方案


Spring Cloud GCP 简化了您的 GCS 配置。

您可以将存储支持添加到您的应用程序。然后,通过spring.cloud.gcp.storage.credentials.location属性指定服务帐户凭据的位置,或者使用 Google Cloud SDK 使用应用程序默认凭据登录

这将自动为您提供一个完全配置的Storage对象,并且@Value(gs://YOUR-BUCKET/YOUR-FILE)应该可以正常工作。


推荐阅读