Use Java 11 with Google Cloud Functions

Introduction

In May 2020, Google Cloud Functions supported Java 11 in beta. Here This article explains how to actually deploy a Java 11 application that is triggered by an HTTP request.

Cloud Shell is used for the operation.

Maven preparation

First, prepare from the pom file required for Maven. Dependencies on functions-framework-api required to run with Cloud Functions Describe 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 as a 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>
        <!--Include Function Maven plugin to allow 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 using an HTTP request as a trigger, the functions-framework-api com.google.cloud.functions.HttpFunction You need to implement the interface. The only method to implement is the service method, and describe the content you want to process in this method.

In this article, it is an application that returns the result when hitting my user ID with Qiita API. I used type inference for local variables as much as possible to make it look like Java11, and skipped requests using java.net.http.HttpRequest.

The request parameters when calling Cloud Functions are stored in com.google.cloud.functions.HttpRequest, which is the argument of the service method. Similarly, you can return the response to the caller by writing the value to the parameter com.google.cloud.functions.HttpResponse.

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 the 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 a call
    var responseFromQiita
        = httpClient.send(requestFromGCF,java.net.http.HttpResponse.BodyHandlers.ofString());
    
    //Content-Type setting, to display Japanese
    response.setContentType("application/json; charset=utf-8");

    //To the person who called Cloud Function the value obtained from Qiita API
    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 say "BUILD SUCCESS", you are successful. Once compiled, run it in your local environment.

$ mvn function:run

When you run it, the start log will appear in the terminal, so open another terminal and run curl.

$ curl localhost:8080
{"description":~~~ Abbreviation ~~~~~"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

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

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

I was able to confirm that the application created with Java 11 could be deployed to Cloud Functions.

Recommended Posts

Use Java 11 with Google Cloud Functions
Create Java applications with IBM Cloud Functions
Use Lambda Layers with Java
Use Thymeleaf with Azure Functions
Use Ruby with Google Colab
Use SpatiaLite with Java / JDBC
Use java with MSYS and Cygwin
Use Microsoft Graph with standard Java
Use Azure Bing SpellCheck with Java
Use JDBC with Java and Scala.
[Google Cloud] Getting Started with Docker
Work with Google Sheets from Java
Google Cloud Platform with Spring Boot 2.0.0
[JaCoCo (Java Code Coverage)] Use with NetBeans
google java format
[Java] Use Collectors.collectingAndThen
Try using Firebase Cloud Functions on Android (Java)
How to use Java framework with AWS Lambda! ??
I want to use java8 forEach with index
How to use Java API with lambda expression
Use Matplotlib from Java or Scala with Matplotlib4j
[Java] Get images with Google Custom Search API
[JAVA] [Spring] [MyBatis] Use IN () with SQL Builder
How to use Alibaba Cloud LOG Java Producer
Get along with Java containers in Cloud Run
[Android] [Java] Download images on GCS (Google Cloud Storage) with Stream using Glide
Use fast Mapping library MapStruct with Lombok and Java 11
How to call functions in bulk with Java reflection
Use ProGuard with Gradle
Change seats with java
Install Java with Ansible
I tried using Google Cloud Vision API in Java
Azure functions in java
Use Puphpeteer with Docker
Use aggregate queries (Count) with Azure CosmosDB Java SDK
Comfortable download with JAVA
Use XVim2 with Xcode 12.0.1
Use CentOS with LXD
Play with Java function nodes that can use Java with Node-RED
Switch java with direnv
Use OpenCV in Java
I dealt with Azure Functions not working in Java
Use ngrok with Docker
Use webmock with Rspec
Download Java with Ansible
Let's scrape with Java! !!
Use java1.7 (zulu7) under a specific directory with jenv
Use WebJars with Gradle
Build Java with Wercker
Use PreparedStatement in Java
Use jlink with gradle
Serverless Java EE starting with Quarkus and Cloud Run
Endian conversion with JAVA
Use Java included with Android Studio to build React Native
Run analysis with OpenJDK11 Java Flight Recorder + Google Kubernetes Engine
Initial setting method when making Alexa Skill with JAVA (Cloud9)
I want to implement various functions with kotlin and java!
Easy BDD with (Java) Spectrum?
Java multi-project creation with Gradle
Getting Started with Java Collection
Use GDAL with Python with Docker