Professional Documents
Culture Documents
Refcard 319 Getting Started With Quarkus 2021
Refcard 319 Getting Started With Quarkus 2021
CONTENTS
∙ Key Benefits
∙ Getting Started
∙ JAX-RS
With Quarkus
∙ Health Checks
∙ Container Images
∙ And more!
1
Build here.
Go anywhere.
SPONSOR FULL-PAGE AD HERE
Join now
REFCARD | GETTING STARTED WITH QUARKUS
./mvnw compile quarkus:dev • Creating an environment file named .env in the current
working directory (GREETING_MESSAGE=Namaste)
This service is started locally and you can use a curl command on
• Creating an external config directory under the current work-
the http://localhost:8080/hello URL to get a response from
ing directory (config/application.properties)
the service.
• Creating an application.properties file in the src/
You can make any changes in the org.acme.quickstart. main/resources directory within the project
GreetingResource source class, (i.e., change the return value from
hello to aloha), and you can execute a curl command on http:// You can set additional configuration files by using the smallrye.
localhost:8080/hello URL and get the updated response without config.locations property.
@GET
greetings.message=Hello World!!
@Produces(MediaType.APPLICATION_JSON)
public List<Developer> getAllDevelopers() {}
Then you can inject the configuration value into any class field:
@DELETE
Quarkus has three different default profiles that can be set by starting
@Path("{id}")
the property with %: @Produces(MediaType.APPLICATION_JSON)
public Response deleteDeveloper(@PathParam("id")
• dev when running in quarkus:dev mode Long id) {}
priority):
Or:
MICROPROFILE SPEC FOR CLOUD used in several elements, such as a CDI bean, JAX-RS resource, or
(KUBERNETES)-NATIVE APPLICATIONS MicroProfile REST Client.
RESTFUL WEB CLIENT
./mvnw
quarkus:add-extension -Dextensions="smallrye-fault-
Quarkus integrates with MicroProfile REST clients to invoke other
tolerance"
RESTful web services.
@RegisterRestClient
Fallback Action @Fallback fallbackMethod
public interface WorldClockService {
@GET
Timeout @Timeout unit
@Path("/json/{where}/now")
@Produces(MediaType.APPLICATION_JSON)
failOn, skipOn,
WorldClock getNow(@PathParam("where") String
delay, delayUnit,
where);
Circuit Breaker @CircuitBreaker requestVolumeThreshold,
}
failureRatio,
successThreshold
Then you need to configure the URL of the service in application.
properties by using the fully qualified name of the class: Bulkhead — waitingTaskQueue (only
Thread Pool/ @Bulkhead valid with @Asynchronous
org.acme.greetings.WorldClockService/mp-rest/ Semaphore semaphore mode)
url=http://worldclockapi.com
AUTOMATIC RETRIES
Last, you need to inject the interface into the classes that require this
client: An automatic retry is executed when the getNow method throws an
@Inject
exception.
@RestClient
@Retry(maxRetries = 1)
WorldClockService worldClockService;
@Fallback(fallbackMethod = "fallbackMethod")
WorldClock getNow(){}
Tip: If the invocation happens within JAX-RS, you can
propagate the headers' value from the incoming request to the public String fallbackMethod() {
outgoing response by specifying them in the org.eclipse. return WorldClock.now();
microprofile.rest.client.propagateHeaders }
The REST client also supports asynchronous calls by returning ExecutionContext parameter.
This type of logic can then be set in the annotation as the value @Liveness
@ApplicationScoped
@Fallback(RecoverFallback.class).
public class DatabaseHealthCheck implements
Circuit breaker is used to detect failures and encapsulate the logic, public HealthCheckResponse call() {
HealthCheckResponseBuilder responseBuilder =
preventing a failure to occur repeatedly.
HealthCheckResponse.named("Database conn");
@CircuitBreaker(requestVolumeThreshold = 4,
failureRatio = 0.75, delay = 1000) try {
checkDatabaseConnection();
@Bulkhead(5)
Below is the code for accessing the /q/health endpoint to get a
@Retry(maxRetries = 4, delay = 1000, retryOn =
BulkheadException.class)
JSON document describing the status of the application:
WorldClock getNow(){}
{
"status": "UP",
CONFIGURATION "checks": [
{
You can override annotation parameters via the configuration file "name": "Database conn",
using the following property: "status": "UP",
"data": {
[classname/methodname/]annotation/parameter: "connection": true
# Method scope }
org.acme.greetings.WorldClockService/getNow/Retry/ }
maxDuration=30 ]
# Class scope }
org.acme.greetings.WorldClockService/Retry/
maxDuration=3000 The status code is 200 OK if the global status is UP and 503 Service
# Global
Unavailable if the status is DOWN. The /q/health/ready and /q/
Retry/maxDuration=3000
health/live endpoints can be used to get results individually from
readiness or liveness probes.
HEALTH CHECKS
Kubernetes relies on the concept of liveness and readiness probes Since health checks are CDI beans, you can create health checks
to monitor the state of the pod and decide if it should be restarted directly in a class:
or, for example, if it should start accepting traffic. Quarkus integrates
import javax.enterprise.inject.Produces;
with the MicroProfile Health spec to provide health checks to
import io.smallrye.health.HealthStatus;
Kubernetes.
public class ApplicationHealthChecks {
./mvnw quarkus:add-extension -Dextensions="smallrye-
health"
@Liveness
@ApplicationScoped
To create a custom health check, you need to implement the @Produces
HealthCheck interface and annotate the class with @Readiness
Continued on next page.
and/or @Liveness.
this::isDbUpAndRunning); -Dextensions="smallrye-opentracing"
}
The below code is used for tracing configuration:
private boolean isDbUpAndRunning() {}
quarkus.jaeger.service-name=myservice
}
quarkus.jaeger.sampler-type=const
quarkus.jaeger.sampler-param=1
Some extensions provide readiness probes by default. To mention
quarkus.jaeger.endpoint=http://localhost:14268/api/
some of them: DataSource, Kafka, Kafka-Streams, MongoDB, traces
Neo4J, Artemis, Vault, gRPC, Cassandra, and Redis.
By default, requests sent to any endpoint will be traced without any
METRICS code changes being required. You can customize traces by injecting
Quarkus can utilize the Micrometer metrics library for runtime and the Tracer class:
If you want to disable tracing at the class or method level, you can
With the Prometheus registry extension added, the generated output
use the @Traced annotation.
format follows the Prometheus format.
@Produces
@Singleton SECURITY AND JWT
public MeterFilter configureAllRegistries() {
In microservices architectures, using stateless services is one of the
return MeterFilter.commonTags(Arrays.asList(
Tag.of(“env”, deploymentEnv)));
goals you'd like to achieve. For security and, more specifically, the
} authorization process, Quarkus integrates with the MicroProfile JWT
} RBAC spec.
JVM MODE
curl -H \"Authorization: Bearer eyJraWQiOi... \".
lifetime greater than @RequestScoped, then you need to use the quarkus/gettingstarted .
javax.enterprise.inject.Instance interface.
CONTAINER IMAGES
An example of the minimal configuration parameters is:
You can leverage Quarkus to generate and release container images.
mp.jwt.verify.publickey.location=META-INF/resources/ Three methods are supported based on the registered extension:
publicKey.pem
• Jib (GoogleContainerTools/jib: Build container images for
• Docker
quarkus.smallrye- Determine if the JWT
true • ./mvnw quarkus:add-extension -Dexten-
jwt.enabled extension is enabled.
sions=”quarkus-container-image-docker”
The name of the java.
• S2I (openshift/source-to-image: A tool for building artifacts
security.Provider
quarkus.smallrye- from source and injecting into container images)
SunRsaSign that supports
jwt.rsa-sig-provider
SHA256withRSA • ./mvnw quarkus:add-extension -Dexten-
signatures.
sions=”quarkus-container-image-s2i”
mp.jwt.verify. Public Key text itself to
publickey be supplied as a string.
PROPERTY DEFAULT DESCRIPTION
quarkus.kubernetes.mounts.github-token.path=/
quarkus.container-
Additional tags of the deployment/github
image.additional-
container image. quarkus.kubernetes.mounts.github-token.read-only=true
tags
quarkus.kubernetes.secret-volumes.github-token.volume-
quarkus.container- The registry to use for
docker.io name=github-token
image.registry pushing.
quarkus.kubernetes.secret-volumes.github-token.secret-
name=greeting-security
quarkus.container- The username to access
quarkus.kubernetes.secret-volumes.github-token.default-
image.username the registry.
mode=420
quarkus.kubernetes.env.vars.my-env-var=foobar
quarkus.container- Boolean to set if the
false quarkus.kubernetes.env.configmaps=my-config-
image.build image should be built.
map,another-config-map
quarkus.kubernetes.env.secrets=my-secret,my-other-
quarkus.container- Boolean to set if the
false secret
image.push image should be pushed.
quarkus.kubernetes.resources.requests.memory=64Mi
To build and push a container image using the Quarkus extension, quarkus.kubernetes.resources.limits.cpu=1000m
you need to run the following command:
Resources can be added under the src/main/kubernetes directory.
./mvnw package -Dquarkus.container-image.push=true
PARAMETER DEFAULT DESCRIPTION
Tip: You can use native flags and container image
tags together to publish a container image containing quarkus.kubernetes. Generates and deploys the
false
a native image. deploy resources to Kubernetes.
quarkus.kubernetes.namespace=mynamespace quarkus.package.type=mutable-jar
quarkus.live-reload.password=changeit
quarkus.kubernetes.replicas=3
quarkus.container-image.build=true
quarkus.kubernetes.labels.foo=bar quarkus.kubernetes-client.trust-certs=true
quarkus.kubernetes.expose=true
quarkus.kubernetes.annotations.foo=bar quarkus.kubernetes.env-vars.quarkus-launch-devmode.
value=true
quarkus.kubernetes.readiness-probe.period-seconds=45
Notice the application is configured to start in dev mode — even
./mvnw quarkus:remote-dev
This Refcard has shown how to use some of the most common
Now any changes made locally will automatically be reloaded by the extensions within the Quarkus ecosystem. Please visit https://code.
application in the Kubernetes cluster. quarkus.io for a list of all extensions as well as https://qurkus.io/
guides/ for further information on building Quarkus applications.
Alex is a Director of Developer Experience at Red Hat. He is passionate about Java and software automation, and he believes
in the open source software model.
Alex is the creator of the NoSQLUnit project, a member of the JSR374 (Java API for JSON Processing) Expert Group, the
co-author of the Testing Java Microservices book from Manning, and a contributor to several open source projects. A Java
Champion since 2017, international speaker and teacher at Salle URL University, he has talked about new testing techniques
for microservices and continuous delivery in the 21st century.