Fork me on GitHub

Springboot之Google cloud Storage

JDK version: 1.8
Gradle version: 6.8

生成Credential

gcloud auth application-default login --impersonate-service-account

Gradle config

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.1.6.RELEASE'
    id "io.spring.dependency-management" version "1.0.8.RELEASE"
}

group = 'org.example'
version = '1.0-SNAPSHOT'

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
    maven { url "https://google.oss.sonatype.org/service/local/staging/deploy/maven2/" }
    maven { url "https://google.oss.sonatype.org/content/repositories/snapshots" }
    mavenLocal()
}

dependencies {
    implementation 'com.google.guava:guava:30.1-jre'
    implementation('org.springframework.boot:spring-boot-starter-web')
    implementation group: 'com.google.cloud', name: 'google-cloud-storage', version: '2.42.0'
    testImplementation platform('org.junit:junit-bom:5.10.0')
    testImplementation 'org.junit.jupiter:junit-jupiter'
}

test {
    useJUnitPlatform()
}

Connect to GCP Storage and upload object

// Instantiates a credential
GoogleCredentials googleCredentials = GoogleCredentials.fromStream(
        Objects.requireNonNull(Hello.class.getResourceAsStream("/application_default_credentials.json"))
);

// Instantiates a client
Storage storage = StorageOptions.newBuilder()
                .setCredentials(googleCredentials)
                .build()
                .getService();

// bucket name
String bucketName = "";

// https://cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Storage#com_google_cloud_storage_Storage_create_com_google_cloud_storage_BlobInfo_byte___com_google_cloud_storage_Storage_BlobTargetOption____
// upload file
BlobId blobId = BlobId.of(bucketName, "test");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
storage.create(blobInfo, Files.newInputStream(new File("D:\\test.txt").toPath()));

Page<Blob> blobs = storage.list(bucketName);
for (Blob blob : blobs.iterateAll()) {
    System.out.printf("file %s created.", blob.getName());
}
posted @ 2024-10-08 17:13  逍遥メ风  阅读(11)  评论(0编辑  收藏  举报