Cloud implementation in java

Create and deploy a HTTP Cloud Function by using Java

Note: This content applies only to Cloud Functions (1st gen). See Cloud Functions version comparison for more information.

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

  • An HTTP function, which you invoke from standard HTTP requests.
  • An event-driven function, which you use to handle events from your Cloud infrastructure, such as messages on a Cloud 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.

Learn more: For more details, read about HTTP functions and event-driven functions.

Guide structure

Creating a GCP project using Google Cloud SDK

  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. Note: If you don’t plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project. Go to project selector
  3. Make sure that billing is enabled for your Google Cloud project.
  4. Enable the Cloud Functions and Cloud Build APIs. Enable the APIs
  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project. Note: If you don’t plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project. Go to project selector
  6. Make sure that billing is enabled for your Google Cloud project.
  7. Enable the Cloud Functions and Cloud Build APIs. Enable the APIs
  8. Install and initialize the Google Cloud SDK.
  9. Update and install gcloud components:
Читайте также:  Css text hover animations

Creating a 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 
 mkdir %HOMEPATH%\helloworld cd %HOMEPATH%\helloworld 
mkdir -p src/main/java/functions touch src/main/java/functions/HelloWorld.java 
 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!"); >>

Gradle

  1. Create a directory on your local system for the function code: Linux or Mac OS X:
 mkdir ~/helloworld-gradle cd ~/helloworld-gradle 
 mkdir %HOMEPATH%\helloworld-gradle cd %HOMEPATH%\helloworld-gradle 
 mkdir -p src/main/java/functions touch src/main/java/functions/HelloWorld.java 
 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!"); >>

Specifying 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 section inside the pom.xml file of your project. For this exercise, copy the following contents into your pom.xml file.

 4.0.0 com.example.functions functions-hello-world 1.0.0-SNAPSHOT 11 11    com.google.cloud.functions functions-framework-api 1.1.0 provided      com.google.cloud.functions function-maven-plugin 0.11.0 functions.HelloWorld     

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.0' // 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.1.5' testImplementation 'org.mockito:mockito-core:5.4.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.

Building and testing locally

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

Maven

Run the following command to confirm that your function builds:

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.

To test the function, run the following command:

Gradle

Run the following command to confirm that your function builds:

To test the function, run the following command:

gradle runFunction -Prun.functionTarget=functions.HelloWorld 

If testing completes successfully, it displays the URL you can visit in your web browser to see the function in action: http://localhost:8080/ . You should see a Hello World! message.

Alternatively, you can send requests to this function using curl from another terminal window:

curl localhost:8080 # Output: Hello World! 

Deploying the function

Maven

To deploy the function with an HTTP trigger, run the following command in the helloworld directory:

gcloud functions deploy my-first-function --entry-point functions.HelloWorld --runtime java17 --trigger-http --memory 512MB --allow-unauthenticated 

where my-first-function is the registered name by which your function will be identified in the Google Cloud console, and —entry-point specifies your function’s fully qualified class name (FQN).

Gradle

To deploy the function with an HTTP trigger, run the following command in the helloworld-gradle directory:

gcloud functions deploy my-first-function --entry-point functions.HelloWorld --runtime java17 --trigger-http --memory 512MB --allow-unauthenticated 

where my-first-function is the registered name by which your function will be identified in the Google Cloud console, and —entry-point specifies your function’s fully qualified class name (FQN).

Testing the deployed function

  1. When the function finishes deploying, take note of the httpsTrigger.url property or find it using the following command:
gcloud functions describe my-first-function 
https://GCP_REGION-PROJECT_ID.cloudfunctions.net/my-first-function

Viewing logs

Using the command-line tool

Logs for Cloud Functions are viewable in the Cloud Logging UI, and via the Google Cloud CLI.

To view logs for your function with the gcloud CLI, use the logs read command, followed by the name of the function:

gcloud functions logs read my-first-function

The output should resemble the following:

LEVEL NAME EXECUTION_ID TIME_UTC LOG D my-first-function k2bqgroszo4u 2020-07-24 18:18:01.791 Function execution started D my-first-function k2bqgroszo4u 2020-07-24 18:18:01.958 Function execution took 168 ms, finished with status code: 200 .

Note: There is typically a slight delay between when log entries are created and when they show up in Cloud Logging.

Using the Logging dashboard

You can also view logs for Cloud Functions from the Google Cloud console.

Learn more: For more details, read about writing, viewing, and responding to logs.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2023-07-24 UTC.

Источник

Оцените статью