152. Spring Resources

Spring Resources是许多低级资源的抽象,例如文件系统文件,Classpath 文件,与 Servlet 上下文相关的文件等。SpringCloud GCP 添加了一种新的资源类型:Google Cloud Storage(GCS)对象。

提供了一个 Spring Boot 启动器来自动配置各种存储组件。

使用 Spring Cloud GCP BOM 进行 Maven 坐标:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-gcp-starter-storage</artifactId>
</dependency>

Gradle coordinates:

dependencies {
    compile group: 'org.springframework.cloud', name: 'spring-cloud-gcp-starter-storage'
}

也可以从Spring InitializrGCP Storage条目使用此启动器。

152.1 Google 云存储

Google Cloud Storage 的 Spring Resource Abstraction 允许 GCS 对象使用@Value注解通过其 GCS URL 访问:

@Value("gs://[YOUR_GCS_BUCKET]/[GCS_FILE_NAME]")
private Resource gcsResource;

…或 Spring 应用程序上下文

SpringApplication.run(...).getResource("gs://[YOUR_GCS_BUCKET]/[GCS_FILE_NAME]");

这将在其他可能的操作中创建一个Resource对象,该对象可用于读取该对象。

尽管需要WriteableResource,但也可以写入Resource

@Value("gs://[YOUR_GCS_BUCKET]/[GCS_FILE_NAME]")
private Resource gcsResource;
...
try (OutputStream os = ((WritableResource) gcsResource).getOutputStream()) {
  os.write("foo".getBytes());
}

要将Resource用作 Google Cloud Storage 资源,请将其强制转换为GoogleStorageResource

如果资源路径引用 Google Cloud Storage 上的对象(而不是存储桶),则可以调用getBlob方法以获得Blob。此类型表示 GCS 文件,该文件具有可设置的关联metadata,例如 content-type。 createSignedUrl方法还可用于为 GCS 对象获取signed URLs。但是,创建签名的 URL 要求使用服务帐户凭据创建资源。

Google Cloud Storage 的 Spring Boot Starter 基于 Spring Boot GCP 启动程序提供的CredentialsProvider自动配置spring-cloud-gcp-storage模块所需的Storage bean。

152.1.1 设置 Content Type

您可以从相应的Resource对象设置 Google Cloud Storage 文件的 Content Type:

((GoogleStorageResource)gcsResource).getBlob().toBuilder().setContentType("text/html").build().update();

152.2 Configuration

Google Cloud Storage 的 Spring Boot Starter 提供以下配置选项:

NameDescriptionRequiredDefault value
spring.cloud.gcp.storage.enabled启用 GCP 存储 API。Notrue
spring.cloud.gcp.storage.auto-create-files对不存在的文件进行写入时,在 Google Cloud Storage 上创建文件和存储桶Notrue
spring.cloud.gcp.storage.credentials.location用于与 Google 云端存储 API 进行身份验证的 OAuth2 凭据(如果与Spring Cloud GCP 核心模块中的凭据不同)No
spring.cloud.gcp.storage.credentials.encoded-keyOAuth2 帐户私有密钥的 Base64 编码内容,用于与 Google Cloud Storage API 进行身份验证(如果与Spring Cloud GCP 核心模块中的内容不同)No
spring.cloud.gcp.storage.credentials.scopesOAuth2 scope用于 Spring Cloud GCP 存储凭据Nohttps://www.googleapis.com/auth/devstorage.read_write

152.3 Sample

sample applicationcodelab可用。