Reputation: 217
What are the configurations for GCP to read files from the GCS bucket in spring boot?
Upvotes: 4
Views: 8734
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 :)
gsutil
command that comes with the Cloud SDK.$ BUCKET=spring-bucket-$USER
$ gsutil makebucket gs://$BUCKET
my-file.txt
file to the bucket.$ gsutil copy my-file.txt gs://$BUCKET
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.GcsApplication
Spring Boot app.$ mvn spring-boot:run
Navigate to http://localhost:8080/ in your browser to print the contents of the file you uploaded in step 3.
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
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
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:
Upvotes: 3