The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.
Edit this Page

Google Cloud Functions (Serverless) with Quarkus REST, Undertow, or Reactive Routes

The quarkus-google-cloud-functions-http extension allows you to write microservices with Quarkus REST (Jakarta REST), Undertow (Servlet), Reactive Routes, or Funqy HTTP, and make these microservices deployable to the Google Cloud Functions runtime.

One Google Cloud Functions deployment can represent any number of Jakarta REST, Servlet, Reactive Routes, or Funqy HTTP endpoints.

This technology is considered preview.

In preview, backward compatibility and presence in the ecosystem is not guaranteed. Specific improvements might require changing configuration or APIs, and plans to become stable are under way. Feedback is welcome on our mailing list or as issues in our GitHub issue tracker.

For a full list of possible statuses, check our FAQ entry.

Requisitos previos

To complete this guide, you need:

Solución

This guide walks you through generating a sample project followed by creating three HTTP endpoints written with Jakarta REST APIs, Servlet APIs, Reactive Routes, or Funqy HTTP APIs. Once built, you will be able to deploy the project to Google Cloud.

Si no quieres seguir todos estos pasos, puedes ir directamente al ejemplo completo.

Clone el repositorio Git: git clone https://github.com/quarkusio/quarkus-quickstarts.git o descargue un archivo.

The solution is located in the google-cloud-functions-http-quickstart directory.

Creación del proyecto de Maven

Create an application with the quarkus-google-cloud-functions-http extension. You can use the following Maven command to create it:

CLI
quarkus create app org.acme:google-cloud-functions-http \
    --extension='google-cloud-functions-http,rest-jackson,undertow,reactive-routes,funqy-http' \
    --no-code
cd google-cloud-functions-http

To create a Gradle project, add the --gradle or --gradle-kotlin-dsl option.

For more information about how to install and use the Quarkus CLI, see the Quarkus CLI guide.

Maven
mvn io.quarkus.platform:quarkus-maven-plugin:3.16.3:create \
    -DprojectGroupId=org.acme \
    -DprojectArtifactId=google-cloud-functions-http \
    -Dextensions='google-cloud-functions-http,rest-jackson,undertow,reactive-routes,funqy-http' \
    -DnoCode
cd google-cloud-functions-http

To create a Gradle project, add the -DbuildTool=gradle or -DbuildTool=gradle-kotlin-dsl option.

For Windows users:

  • If using cmd, (don’t use backward slash \ and put everything on the same line)

  • If using Powershell, wrap -D parameters in double quotes e.g. "-DprojectArtifactId=google-cloud-functions-http"

Iniciar sesión en Google Cloud

Login to Google Cloud is necessary for deploying the application. It can be done as follows:

gcloud auth login

Creación de los endpoints

For this example project, we will create four endpoints, one for Quarkus REST (Jakarta REST), one for Undertow (Servlet), one for Reactive routes and one for Funqy HTTP.

These various endpoints are for demonstration purposes. For real life applications, you should choose one of this technology and stick to it.

Si no necesita endpoints de cada tipo, puede eliminar las extensiones correspondientes de su pom.xml.

Quarkus supports Cloud Functions gen 1 and gen 2. For an overview of Cloud Functions gen 2 see this page on the Google Cloud Functions documentation. To use gen 2 you must and add the --gen2 parameter.

The Jakarta REST endpoint

import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;

@Path("/hello")
public class GreetingResource {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello() {
        return "Hello from Quarkus REST";
    }
}

El endpoints del Servlet

import java.io.IOException;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet(name = "ServletGreeting", urlPatterns = "/servlet/hello")
public class GreetingServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(200);
        resp.addHeader("Content-Type", "text/plain");
        resp.getWriter().write("hello");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getReader().readLine();
        resp.setStatus(200);
        resp.addHeader("Content-Type", "text/plain");
        resp.getWriter().write("hello " + name);
    }
}

El endpoints de las rutas reactivas

import static io.quarkus.vertx.web.Route.HttpMethod.GET;

import io.quarkus.vertx.web.Route;
import io.vertx.ext.web.RoutingContext;

public class GreetingRoutes {
    @Route(path = "/vertx/hello", methods = GET)
    void hello(RoutingContext context) {
        context.response().headers().set("Content-Type", "text/plain");
        context.response().setStatusCode(200).end("hello");
    }
}

El endpoints HTTP de Funqy

import io.quarkus.funqy.Funq;

public class GreetingFunqy {
    @Funq
    public String funqy() {
        return "Make it funqy";
    }
}

Construir y desplegar en Google Cloud

Quarkus obliga a un empaquetado de tipo uber-jar para su función, ya que el despliegue de Google Cloud Function requiere un único JAR.

Package your application using the standard mvn clean package command. The result of the previous command is a single JAR file inside the target/deployment directory that contains the classes and the dependencies of the project.

A continuación, podrá utilizar gcloud para desplegar su función en Google Cloud.

We will use the Java 21 runtime, but you can switch to the Java 17 runtime by using --runtime=java17 instead of --runtime=java21 on the deploy commands.
gcloud functions deploy quarkus-example-http \
  --entry-point=io.quarkus.gcp.functions.http.QuarkusHttpFunction \
  --runtime=java21 --trigger-http --allow-unauthenticated --source=target/deployment

El punto de entrada debe ser siempre io.quarkus.gcp.functions.http.QuarkusHttpFunction ya que esta es la clase que integra las Funciones Cloud con Quarkus.

La primera vez que se lanza este comando, puede aparecer el siguiente mensaje de error:

ERROR: (gcloud.functions.deploy) OperationError: code=7, message=Build Failed: Cloud Build has not been used in project <project_name> before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/cloudbuild.googleapis.com/overview?project=<my-project> then retry.

Esto significa que Cloud Build aún no está activado. Para superar este error, abra la URL que se muestra en el error, siga las instrucciones y luego espere unos minutos antes de volver a intentar el comando.

Este comando le dará como salida un httpsTrigger.url que apunta a su función.

A continuación, puede llamar a sus endpoints a través de:

  • For Jakarta REST: {httpsTrigger.url}/hello

  • Para el servlet: {httpsTrigger.url}/servlet/hello

  • Para las rutas reactivas: {httpsTrigger.url}/vertx/hello

  • Para Funqy: {httpsTrigger.url}/funqy

Pruebas locales

La forma más fácil de probar localmente su función es utilizando el JAR invocador de funciones en la nube.

Puede descargarlo a través de Maven utilizando el siguiente comando:

mvn dependency:copy \
  -Dartifact='com.google.cloud.functions.invoker:java-function-invoker:1.3.0' \
  -DoutputDirectory=.

Antes de utilizar el invocador, primero hay que construir la función a través de mvn package.

A continuación, puede utilizarlo para lanzar su función localmente.

java -jar java-function-invoker-1.3.0.jar \
  --classpath target/deployment/google-cloud-functions-http-1.0.0-SNAPSHOT-runner.jar \
  --target io.quarkus.gcp.functions.http.QuarkusHttpFunction
El parámetro --classpath necesita ser establecido en el JAR previamente empaquetado que contiene su clase de función y todas las clases relacionadas con Quarkus.

Sus endpoints estarán disponibles en http://localhost:8080.

¿Qué es lo siguiente?

You can use our Google Cloud Functions Funqy binding to use Funqy, a provider-agnostic function as a service framework, that allow to deploy HTTP function or Background function to Google Cloud.

Related content