Quarkus: Get started with Kubernetes native Java – Floridanewstimes.com

Quarkus is a full-stack open source Java framework released by Red Hat in 2019. Quarkus is an alternative to Spring (although it can also be integrated with Spring), but it has all some interesting features.
Quarkus is designed to be “cloud native” from scratch. That is, it is tailored for various libraries such as Kubernetes, serverless platforms, Apache Kafka (for stream processing) and JAX-RS (for RESTful web services). Quarkus also has a full CDI (Context and Dependency Injection) engine and reactive programming support.
Read a hands-on introduction to Quarkus.
Quarkus supports Maven and Gradle as build tool wrappers, but it also comes with command line interface (CLI) tools.First CLI installation via JBang tool. From the command line, run the code in Listing 1.
// PowerShell:
iex “& { $(iwr https://ps.jbang.dev) } app install –fresh –force [email protected]
When the command is complete, type: quarkus -version I need to return the result.
Create a new app by typing: quarkus create app com.infoworld:my-quarkus:1.0, where com.infoworld Group ID. my-quarkus It is an artifact ID and 1.0 Is the version number.
The command line tools have many options available for configuration. You can see these options by typing: quarkus --help..You can get help for a particular command by typing: quarkus create app --help.. Note that you can define what build tool wrapper to use, etc.
Then go to the new my-quarkus directory and type: quarkus dev.. Quarkus development mode represents a neat approach. It supports hot code loading and allows you to run tests freely without stopping the container. This is why you are given some command options after the dev container is started at the prompt.
This means that you can change your code, such as adding a test, and then run the test with. r..You can also change the log level with h Or stop the container with q..
By default, Quarkus development mode listens only on the local host. If you want to listen on all networks, you can add host parameters.
To create a production app quarkus build Instructions.
If you access localhost: 8080 while the app is running in development mode, you will see the welcome screen as shown in Figure 1.
Inside the new app directory is a src directory that follows a typical Maven layout, with a test test and a main for app files. There are three directories in / src / main: / src / main / resources, where static files reside (including HTML pages that drive pages such as src / main / resources / META-INF / resources / index.html). / src / main / java, here is the backend code and middleware code. And / src / main / docker. Quarkus will generate a default Dockerfile (including Dockerfile.native for running without a JVM).
Any changes you make to the app will take effect when your browser is updated. For example, you can open the src / main / java / com / infoworld / GreetingResource.java file to see the JAX-RS endpoint. If you change the message and reload localhost: 8080 / hello, you will see that the changes have been reflected.
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 “Welcome to the machine”;
    }
}
Quarkus has many features provided through extensions that can be added with commands. To understand what Quarkus supports This Git repositoryIncludes dozens of examples for using Quarkus with, JPA, Kafka, MongoDB, Amazon S3, Knative and more. These examples are also good starting points for developing Quarkus apps using these technologies (hence the name Quick Start).
You can see the extensions installed in the app by running quarkus ext ls.. You can see that currently only quarkus-resteasy is installed.Get a list of available installable modules quarkus ext ls -i..
Installation is quarkus ext add Instructions.
Quarkus comes with a custom-built dependency injection engine called ArC. ArC CDI specifications, And also has its own special features. Overall, ArC systems are simpler and easier to understand than CDI.
Let’s see how to add a service class to use with RESTful resources. Start by creating a new file in /src/main/java/com/infoworld/service/MyService.java. Add the code shown in Listing 3.
import javax.enterprise.context.ApplicationScoped;
import java.util.Random;
@ApplicationScoped
public class MyService {
    public Integer getRandom(){
      Random random = new Random();
      return random.nextInt(100);
    }
}
MyService is a very simple class with a single method. getRandom(), Returns a random integer. Annotated with CDI standard annotation. @ApplicationScoped, It makes it available in the DI system. (CDI scope and context details here.. Please note that the Quarkus CDI is included in the project as it is used by the RESTEasy extension.
Then open the / src / main / java / com / infoworld / GreetingResource.java class and modify it as shown in Listing 4.
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.inject.Inject;
import com.infoworld.service.MyService;
@Path(“/hello”)
public class GreetingResource {
    @Inject
    MyService myService;
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello() {
        return “Welcome to the machine.  Your number is: ” + myService.getRandom();
    }
}
The important factor here is @Inject Annotation.This will make the CDI engine myService Browse to the resource bean created in Listing 4. This is used to generate a random number for the / hello path.
Now go back to the command line where Quarkus dev is running and type: r If you rerun the test, you will see that the RESTEasy endpoint test case fails. Let’s fix it. Open test / java / com / infoworld /GreetingResourceTest.java. Note that this class uses several different test libraries that are already useful by Quarkus. RestAssured Library. Simplifies testing of RESTful endpoints.
Change GreetingResourceTest As you can see in Listing 5.
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.containsString;  // changed
@QuarkusTest
public class GreetingResourceTest {
    @Test
    public void testHelloEndpoint() {
        given()
          .when().get(“/hello”)
          .then()
             .statusCode(200)
             .body(containsString(“machine”));  // changed
    }
}
Only two lines have changed, as mentioned in the comments. Just check if the word “machine” is present in the response body.Now if you run the test in r Command, they pass.
Let’s dig a little deeper into the external REST API ( Star Wars API, Also known as SWAPI) in the service class.Start by running and adding the quarkus-rest-api client quarkus ext add quarkus-rest-client.. Note that you can do this in a separate window while the app is running and Quarkus will apply the extension. It’s pretty impressive.
It also makes it easy to model your data with the rest-client-jackson extension.type quarkus ext add rest-client-jackson..
Create a model class in the new directory src / main / java / com / infoworld / client /Person.java. This is a very simple data transfer object that Jackson enters, as shown in Listing 6.
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
    public String name;
}
Please note that you are using @JsonIgnoreProperties So if there are fields in the source JSON that don’t exist in the model object, no error will be thrown.
In the same directory, create a new class of service that hits the SWAPI endpoint: /src/main/java/com/infoworld/client/SwapiClient.java. See the contents of that file in Listing 7.
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
import org.jboss.resteasy.annotations.jaxrs.PathParam;
import org.jboss.resteasy.annotations.jaxrs.QueryParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.util.Set;
@RegisterRestClient
public interface SwapiClient {
    @GET
    @Path(“/people/{id}”)
    @Produces(“application/json”)
    Person getById(@PathParam Integer id);
}
Notice that the interface is registered as a REST client. @RegisterRestClient Annotation.Method getById It is also annotated to define the GETHTTP method found as a hit as follows: "/people/{id}", where id Provided by a call to getById(@PathParam Integer id) Method. It is defined here using the same annotations that define a RESTful client that is a RESTful endpoint.
But where is the endpoint route defined?open src/main/resources/application.properties Add the two lines shown in Listing 8.
Details about these properties and how they are connected to your application are available. here..
Then update the GreetingResource to use the new client service, as shown in Listing 9.
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.inject.Inject;
import com.infoworld.service.MyService;
import com.infoworld.client.SwapiClient;
import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.jboss.resteasy.annotations.jaxrs.PathParam;
@Path(“/hello”)
public class GreetingResource {
@Inject
MyService myService;
@Inject
@RestClient
SwapiClient swapiClient;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return “Hello, your Star Wars character is: ” + swapiClient.getById(myService.getRandom()).name;
}
}
Currently injecting the rest of the clients into swapiClient Variables and calls getById A method that uses a random ID from a previously created random number service. This will return a response similar to the following from localhost: 8080 / hello:
This was a whirlwind tour of some of Quarkus’s power, but it was just the beginning. Quarkus is arguably a good alternative to Spring and is under active development, with frequent additions of new and useful features. The next time you get to the Java framework, consider Quarkus.
All code for this tutorial is available here..
Copyright © 2021 IDG Communications, Inc.
Quarkus: Get started with Kubernetes native Java
Source link Quarkus: Get started with Kubernetes native Java

source