[Java] Use Java 11 with Google Cloud Functions

2 minute read

Introduction

In May 2020, Google Cloud Functions supported Java 11 beta version. Here In this article, I will explain how to actually deploy a Java 11 application that is triggered by an HTTP request.

Cloud Shell is used for the operation.

Preparation of #Maven First, prepare from the pom file required for Maven. Dependency on functions-framework-api required to operate with Cloud Functions and Describes the plugin required to run locally.

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>example</groupId>
  <artifactId>functions-hello-world</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <properties>
    <maven.compiler.target>11</maven.compiler.target>
    <maven.compiler.source>11</maven.compiler.source>
  </properties>

  <dependencies>
    <!-- Put Functions Framework for Java in dependency -->
    <dependency>
      <groupId>com.google.cloud.functions</groupId>
      <artifactId>functions-framework-api</artifactId>
      <version>1.0.1</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <!-- Insert Function Maven plugin and enable local execution -->
        <groupId>com.google.cloud.functions</groupId>
        <artifactId>function-maven-plugin</artifactId>
        <version>0.9.3</version>
        <configuration>
          <functionTarget>CloudFunctionsForJava</functionTarget>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

program

Next, prepare the program. When moving an HTTP request as a trigger, com.google.cloud.functions.HttpFunction of functions-framework-api You need to implement the interface. The only method to implement is the service method, and describe the contents you want to process in this method.

In this article, it is an application that returns the result when I hit my user ID with Qiita API. In order to make it Java11-like, I use type inference for local variables and skip the request using java.net.http.HttpRequest.

Request parameters etc. when Cloud Functions are called are stored in com.google.cloud.functions.HttpRequest which is an argument of service method. Similarly, by writing the value to the parameter com.google.cloud.functions.HttpResponse, the response can be returned to the caller.

CloudFunctionsForJava.java


import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;

public class CloudFunctionsForJava implements HttpFunction {

  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException, InterruptedException {
    
    //Preparing to call Qiita API
    var httpClient = HttpClient.newHttpClient();
    var requestFromGCF = java.net.http.HttpRequest
            .newBuilder(URI.create("https://qiita.com/api/v2/users/shuichiro"))
            .header("Content-Type", "application/json; charset=utf-8")
            .build();

    // make the call
    var responseFromQiita
        = httpClient.send(requestFromGCF,java.net.http.HttpResponse.BodyHandlers.ofString());
    
    //Set Content-Type, to display Japanese
    response.setContentType("application/json; charset=utf-8");

    //Set the value obtained from Qiita API to the person who called Cloud Function
    var writer = response.getWriter();
    writer.write(responseFromQiita.body());
  }
}

The location of the created program and pom is as follows.

$ tree
.
├── pom.xml
└── src
    └── main
        └── java
            └── CloudFunctionsForJava.java

test

First, compile.

$ mvn compile

It will take some time, but if you see “BUILD SUCCESS”, you are successful. Once it compiles, run it locally.

$ mvn function:run

When you execute it, the log that started in the terminal appears, so open another terminal and execute curl.

$ curl localhost:8080
{"description": ~~~~~~~~~ "website_url":""}

You can see that the result of Qiita API is displayed.

Deploy

Finally, actually deploy to Cloud Functions. Deploy with the following command. The trigger is an HTTP request and it can be executed without authentication.

$ gcloud functions deploy java-function --entry-point CloudFunctionsForJava --runtime java11 --trigger-http --memory 512MB --allow-unauthenticated

The deployment will be completed in a few minutes, so hit the URL displayed at the time of deployment.

$ curl https://us-central1-YOUR_PROJECT_ID.cloudfunctions.net/java-function
{"description": ~~~~~~~~~ "website_url":""}

We were able to confirm that the application created with Java11 could be deployed to Cloud Functions.