Akhil Suseelan
Akhil Suseelan

Reputation: 217

How to access GCS bucket in springboot?

What are the configurations for GCP to read files from the GCS bucket in spring boot?

Upvotes: 4

Views: 8734

Answers (2)

Pievis
Pievis

Reputation: 1994

You could use Spring Cloud GCP Storage component, easy to add to your project via gradle/maven.

You can find a starter example here :)

Running the example

  1. Make sure that you have the Cloud SDK configured by following these instructions.
  2. Create a new bucket in Google Cloud Storage. You can use the gsutil command that comes with the Cloud SDK.
$ BUCKET=spring-bucket-$USER
$ gsutil makebucket gs://$BUCKET
  1. Transfer the local my-file.txt file to the bucket.
$ gsutil copy my-file.txt gs://$BUCKET
  1. Edit the src/main/resources/application.properties and set the gcs-resource-test-bucket property to the name of your bucket that you created in Step 2.
  2. Start the GcsApplication Spring Boot app.
$ mvn spring-boot:run
  1. Navigate to http://localhost:8080/ in your browser to print the contents of the file you uploaded in step 3.

  2. To update the file contents, send a POST request to the same endpoint using curl:

$ curl -d 'new message' -H 'Content-Type: text/plain' localhost:8080

You should see a confirmation that the contents of the file were updated.

Upvotes: 2

Srikanta
Srikanta

Reputation: 1147

You can autowire the Storage class to work with the bucket (CRUD operations).

@Autowired
private Storage storage;

public void store(InputStream OBJECT_TO_BE_STORED){
  Blob blob = storage.get(BUCKET_NAME).create(OBJECT_NAME, OBJECT_TO_BE_STORED);
}

Following properties need to be defined in the application.properties

  • spring.cloud.gcp.project-id
  • spring.cloud.gcp.credentials.location
  • Property KV for bucket name

Maven should have the following dependencies:

        <dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-gcp-dependencies</artifactId>
            <version>1.2.3.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
   </dependencyManagement>

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

Reference:

  1. https://docs.spring.io/spring-cloud-gcp/docs/1.2.6.RELEASE/reference/html/#spring-cloud-gcp-core
  2. https://docs.spring.io/spring-cloud-gcp/docs/1.2.6.RELEASE/reference/html/#cloud-storage

Upvotes: 3

Related Questions