Google Cloud Functions (Serverless) con RESTEasy Reactive, Undertow o Reactive Routes
previewThe quarkus-google-cloud-functions-http extension allows you to write microservices with RESTEasy Reactive (JAX-RS),
Undertow (Servlet), Reactive Routes, or Funqy HTTP, and make these microservices deployable to the Google Cloud Functions runtime.
Una implementación de Google Cloud Functions puede representar cualquier número de endpoints JAX-RS, Servlet, Rutas Reactivas o Funqy HTTP.
|
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:
-
Roughly 15 minutes
-
An IDE
-
JDK 11+ installed with
JAVA_HOMEconfigured appropriately -
Apache Maven 3.8.6
-
Optionally the Quarkus CLI if you want to use it
-
Una cuenta de Google Cloud. Las cuentas gratuitas funcionan.
Solución
This guide walks you through generating a sample project followed by creating three HTTP endpoints written with JAX-RS 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:
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 RESTEasy (JAX-RS), 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 JAX-RS endpoint
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/hello")
public class GreetingResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Hello from RESTEasy Reactive";
}
}
El endpoints del Servlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.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");
}
}
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 17 runtime but you can switch to the Java 11 runtime by using --runtime=java11 instead of --runtime=java17 on the deploy commands.
|
gcloud functions deploy quarkus-example-http \
--entry-point=io.quarkus.gcp.functions.http.QuarkusHttpFunction \
--runtime=java17 --trigger-http --allow-unauthenticated --source=target/deployment
|
El punto de entrada debe ser siempre |
|
La primera vez que se lanza este comando, puede aparecer el siguiente mensaje de error:
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 JAX-RS: {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.1.1' \
-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.1.1.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 que sigue?
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.