Create and deploy an HTTP Cloud Run function with Java

This guide takes you through the process of writing a Cloud Run function using the Java runtime. There are two types of Cloud Run functions:

  • An HTTP function, which you invoke from standard HTTP requests.
  • An event-driven function, which is triggered by events in your Cloud infrastructure, such as messages on a Pub/Sub topic or changes in a Cloud Storage bucket.

The document shows how to create a simple HTTP function and build it using either Maven or Gradle.

For more detail, read writing HTTP functions and writing event-driven functions.

Before you begin

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Cloud Logging APIs.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Cloud Logging APIs.

    Enable the APIs

  8. Install and initialize the Google Cloud SDK.
  9. Update and install gcloud components with the following command.
    gcloud components update
  10. Prepare your development environment.

    Go to the Java setup guide

Create your function

This section describes how to create a function.

Maven

  1. Create a directory on your local system for the function code:

    Linux or Mac OS X:

     mkdir ~/helloworld
     cd ~/helloworld
    

    Windows:

     mkdir %HOMEPATH%\helloworld
     cd %HOMEPATH%\helloworld
    
  2. Create the project structure to contain the source directory and source file.

    mkdir -p ~/helloworld/src/main/java/functions
    touch ~/helloworld/src/main/java/functions/HelloWorld.java
    
  3. Add the following contents to the HelloWorld.java file:

    
    package functions;
    
    import com.google.cloud.functions.HttpFunction;
    import com.google.cloud.functions.HttpRequest;
    import com.google.cloud.functions.HttpResponse;
    import java.io.BufferedWriter;
    import java.io.IOException;
    
    public class HelloWorld implements HttpFunction {
      // Simple function to return "Hello World"
      @Override
      public void service(HttpRequest request, HttpResponse response)
          throws IOException {
        BufferedWriter writer = response.getWriter();
        writer.write("Hello World!");
      }
    }

    This example function outputs the greeting "Hello World!"

Gradle

  1. Create a directory on your local system for the function code:

    Linux or Mac OS X:

     mkdir ~/helloworld-gradle
     cd ~/helloworld-gradle
    

    Windows:

     mkdir %HOMEPATH%\helloworld-gradle
     cd %HOMEPATH%\helloworld-gradle
    
  2. Create the project structure to contain the source directory and source file.

     mkdir -p src/main/java/functions
     touch src/main/java/functions/HelloWorld.java
    
  3. Add the following contents to the HelloWorld.java file:

    
    package functions;
    
    import com.google.cloud.functions.HttpFunction;
    import com.google.cloud.functions.HttpRequest;
    import com.google.cloud.functions.HttpResponse;
    import java.io.BufferedWriter;
    import java.io.IOException;
    
    public class HelloWorld implements HttpFunction {
      // Simple function to return "Hello World"
      @Override
      public void service(HttpRequest request, HttpResponse response)
          throws IOException {
        BufferedWriter writer = response.getWriter();
        writer.write("Hello World!");
      }
    }

    This example function outputs the greeting "Hello World!"

Specify dependencies

The next step is to set up dependencies:

Maven

Change directory to the helloworld directory you created above, and create a pom.xml file:

 cd ~/helloworld
 touch pom.xml

To manage dependencies using Maven, specify the dependencies in the <dependencies> section inside the pom.xml file of your project. For this exercise, copy the following contents into your pom.xml file.

<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>com.example.functions</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>
    <!-- Required for Function primitives -->
    <dependency>
      <groupId>com.google.cloud.functions</groupId>
      <artifactId>functions-framework-api</artifactId>
      <version>1.1.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <!--
          Google Cloud Functions Framework Maven plugin

          This plugin allows you to run Cloud Functions Java code
          locally. Use the following terminal command to run a
          given function locally:

          mvn function:run -Drun.functionTarget=your.package.yourFunction
        -->
        <groupId>com.google.cloud.functions</groupId>
        <artifactId>function-maven-plugin</artifactId>
        <version>0.11.0</version>
        <configuration>
          <functionTarget>functions.HelloWorld</functionTarget>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

See helloworld for a complete sample based on Maven.

Gradle

Change directory to the helloworld-gradle directory you created above, and create a build.gradle file:

 cd ~/helloworld-gradle
 touch build.gradle

To manage dependencies using Gradle, specify the dependencies in the build.gradle file of your project. For this exercise, copy the following contents into your build.gradle file. Note that this build.gradle file includes a custom task to help you run functions locally.

apply plugin: 'java'

repositories {
  jcenter()
  mavenCentral()
}
configurations {
    invoker
}

dependencies {
  // Every function needs this dependency to get the Functions Framework API.
  compileOnly 'com.google.cloud.functions:functions-framework-api:1.1.0'

  // To run function locally using Functions Framework's local invoker
  invoker 'com.google.cloud.functions.invoker:java-function-invoker:1.3.1'

  // These dependencies are only used by the tests.
  testImplementation 'com.google.cloud.functions:functions-framework-api:1.1.0'
  testImplementation 'junit:junit:4.13.2'
  testImplementation 'com.google.truth:truth:1.4.0'
  testImplementation 'org.mockito:mockito-core:5.10.0'

}

// Register a "runFunction" task to run the function locally
tasks.register("runFunction", JavaExec) {
  main = 'com.google.cloud.functions.invoker.runner.Invoker'
  classpath(configurations.invoker)
  inputs.files(configurations.runtimeClasspath, sourceSets.main.output)
  args(
    '--target', project.findProperty('run.functionTarget') ?: '',
    '--port', project.findProperty('run.port') ?: 8080
  )
  doFirst {
    args('--classpath', files(configurations.runtimeClasspath, sourceSets.main.output).asPath)
  }
}

See helloworld-gradle for a complete sample based on Gradle.

Build and test your function locally

Before deploying the function, you can build and test it locally:

Maven

  1. Run the following command to confirm that your function builds:

    mvn compile
    

    Another option is to use the mvn package command to compile your Java code, run any tests, and package the code up in a JAR file within the target directory. You can learn more about the Maven build lifecycle here.

  2. Start your function with the following command:

    mvn function:run
    
  3. Test your function by visiting http://localhost:8080 in a browser or by running curl localhost:8080 from another window.

    See Sending requests to local functions for more detail.

Gradle

  1. Run the following command to confirm that your function builds:

    gradle build
    
  2. Start your function with the following command:

    gradle runFunction -Prun.functionTarget=functions.HelloWorld
    
  3. Test your function by visiting http://localhost:8080 in a browser or by running curl localhost:8080 from another window.

    See Sending requests to local functions for more detail.

Deploy your function

To deploy your function, run the following command in the helloworld directory (if you're using maven) or the helloworld-gradle directory (for gradle):

  gcloud functions deploy java-http-function \
    --gen2 \
    --entry-point=functions.HelloWorld \
    --runtime=java21 \
    --region=REGION \
    --source=. \
    --trigger-http \
    --allow-unauthenticated

Replace REGION with the name of the Google Cloud region where you want to deploy your function (for example, us-west1).

The optional --allow-unauthenticated flag lets you reach your function without authentication.

java-http-function is the registered name by which your function is identified in the Google Cloud console, and --entry-point specifies your function's fully qualified class name (FQN).

Test your deployed function

  1. After the function deploys, note the uri property from the output of the gcloud functions deploy command, or retrieve it with the following command:

    gcloud functions describe java-http-function \
      --region=REGION
    

    Replace REGION with the name of the Google Cloud region where you deployed your function (for example, us-west1).

  2. Visit this URL in your browser. The function returns a "Hello World!" message.

View your function's logs

View the logs with the command-line tool

You can review your function's logs with the Cloud Logging UI or via the Google Cloud CLI.

To view logs for your function with the gcloud CLI, use the logs read command:

    gcloud functions logs read \
      --gen2 \
      --limit=10 \
      --region=REGION \
      java-http-function

Replace REGION with the name of the Google Cloud region where you deployed your function (for example, us-west1).

The output resembles the following:

LEVEL: I
NAME: my-first-function
TIME_UTC: 2023-05-29 23:09:57.708
LOG:

LEVEL: I
NAME: my-first-function
TIME_UTC: 2023-05-29 23:05:53.257
LOG: Default STARTUP TCP probe succeeded after 1 attempt for container "my--first--function-1" on port 8080.

LEVEL:
NAME: my-first-function
TIME_UTC: 2023-05-29 23:05:53.248
LOG: 2023-05-29 23:05:53.248:INFO:oejs.Server:main: Started @892ms

View logs with the logging dashboard

To view the logs for your function with the logging dashboard, open the Cloud Run functions Overview page and click the name of your function from the list, then click the Logs tab.