Use the Micronaut Object Storage API to store files in Google Cloud Storage
Learn how to upload and retrieve files from Google Cloud Storage using the Micronaut Object Storage API
On this guide
In this section
Getting Started
In this guide, we will create a Micronaut application written in Java.
It will be a microservice to store, retrieve and delete profile pictures for users.
What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOMEconfigured appropriately -
A Google Cloud Platform (GCP) account and a GCP project.
Some of the following commands use jq
jq is a lightweight and flexible command-line JSON processor
Google Cloud Platform
Signup for the Google Cloud Platform
Cloud SDK
Install the Cloud SDK CLI for your operating system.
Cloud SDK includes the gcloud command-line tool. Run the init command in your terminal:
gcloud initLog in to your Google Cloud Platform:
gcloud auth loginGoogle Cloud Platform Project
Create a new project with a unique name (replace xxxxxx with alphanumeric characters of your choice):
gcloud projects create micronaut-guides-xxxxxx|
Note
|
In GCP, project ids are globally unique, so the id you used above is the one you should use in the rest of this guide. |
Change your project:
gcloud config set project micronaut-guides-xxxxxxIf you forget the project id, you can list all projects:
gcloud projects listSolution
We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.
-
Download and unzip the source
Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
mn create-app example.micronaut.micronautguide \
--features=object-storage-gcp,graalvm \
--build=gradle \
--lang=java \
--test=junit|
Note
|
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool. If you don’t specify the --lang argument, Java is used as the language.If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.
|
The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.
If you use Micronaut Launch, select Micronaut Application as application type and add object-storage-gcp, and graalvm features.
|
Note
|
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application. |
Create a bucket
Use the Google Cloud CLI to create a bucket:
gcloud storage buckets create gs://micronaut-guide-object-storageThen, configure the bucket name in application.properties:
micronaut.object-storage.gcp.default.bucket=micronaut-guide-object-storageController API
Let’s define an interface with the endpoints of the profile pictures microservice:
And then, an implementation with the required dependencies:
request. When uploading a picture, we will use the host to build an absolute URL for the Location header. Learn more
about Host Resolution.
Upload endpoint
Implement the upload endpoint by receiving the file from the HTTP client via CompletedFileUpload, and the userId path
parameter. Upload it to Google Cloud using
GoogleCloudStorageOperations,
and then return its ETag in an HTTP response header to the client:
object. It also has a getNativeResponse() method that can
be used for accessing the vendor-specific response object, in this case Blob.
<.> We return the absolute URL of the resource in the Location header.
<.> The response object contains some common properties for all cloud vendors, such as the ETag, that is sent in a header to the client.
Download endpoint
For the download endpoint, simply retrieve the entry from the expected key and transform it into a StreamedFile:
GoogleCloudStorageEntry,
which allows accessing the Google Cloud-specific
Blob
<.> We transform the GoogleCloudStorageEntry into an HttpResponse<StreamedFile>.
<.> The response contains not only the file, but also an ETag header.
|
Note
|
The HTTP client could have used the ETag from the upload operation and sent it in an If-None-Match header in the
download request to implement caching,
which then would have to be implemented in the download endpoint. But this is beyond the scope of this guide.
|
Delete endpoint
For the delete endpoint, all we have to do is invoke the delete method with the expected key:
@Override
public void delete(String userId) {
String key = buildKey(userId);
objectStorage.delete(key);
}Running the Application
To run the application, use the ./gradlew run command, which starts the application on port 8080.
Generate a Micronaut Application Native Executable with GraalVM
We will use GraalVM, an advanced JDK with ahead-of-time Native Image compilation, to generate a native executable of this Micronaut application.
Compiling Micronaut applications ahead of time with GraalVM significantly improves startup time and reduces the memory footprint of JVM-based applications.
|
Note
|
Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.
|
GraalVM Installation
sdk install java 25.0.2-graalFor installation on Windows, or for a manual installation on Linux or Mac, see the GraalVM Getting Started documentation.
The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.
Alternatively, you can use the GraalVM Community Edition:
sdk install java 25.0.2-graalceNative Executable Generation
To generate a native executable using Gradle, run:
./gradlew nativeCompileThe native executable is created in build/native/nativeCompile directory and can be run with build/native/nativeCompile/micronautguide.
It is possible to customize the name of the native executable or pass additional parameters to GraalVM:
Testing
Test the application from the command line.
Uploading a profile picture
|
Note
|
If you want to upload a file larger than 1MB, you need to configure: src/main/resources/application.properties |
Assuming you have locally a profile picture in a profile.jpg file, you can send it to your application with:
$ curl -i -F 'fileUpload=@profile.jpg' http://localhost:8080/pictures/alvaro
HTTP/1.1 201 Created
location: http://localhost:8080/pictures/alvaro
ETag: "617cb82e296e153c29b34cccf7af0908"
date: Wed, 14 Sep 2022 12:50:30 GMT
connection: keep-alive
transfer-encoding: chunkedNote the Location and ETag headers.
Use the gcloud CLI to verify that the file has been uploaded to a Google Cloud bucket:
gcloud storage ls --recursive gs://micronaut-guide-object-storageDownload a profile picture
curl http://localhost:8080/pictures/alvaro -O -JThe file will be saved as alvaro.jpg since our download endpoint includes a Content-Disposition: attachment header.
Open it to check that it is actually the same image as profile.jpg.
Delete a profile picture
curl -X DELETE http://localhost:8080/pictures/alvaroThen, check that the file has actually been deleted:
gcloud storage ls --recursive gs://micronaut-guide-object-storageCleaning Up
After you’ve finished this guide, you can clean up the resources you created on Google Cloud Platform so you won’t be billed for them in the future. The following sections describe how to delete or turn off these resources.
Deleting the project
The easiest way to eliminate billing is to delete the project you created for the tutorial.
|
Warning
|
Deleting a project has the following consequences:
|
Via the CLI
To delete the project using the Cloud SDK, run the following command, replacing YOUR_PROJECT_ID with the project ID:
gcloud projects delete YOUR_PROJECT_IDVia the Cloud Platform Console
In the Cloud Platform Console, go to the Projects page.
In the project list, select the project you want to delete and click Delete project. After selecting the checkbox next to the project name, click Delete project
In the dialog, type the project ID, and then click Shut down to delete the project.
Deleting or turning off specific resources
You can individually delete or turn off some of the resources that you created during the tutorial.
Next Steps
-
Read more about Micronaut Object Storage.
-
Discover Google Cloud Storage.
License
|
Note
|
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images). |