banner



How To Consuming Restful Web Service Using Jersey

Learn how to use a reactive JAX-RS client to asynchronously invoke RESTful microservices over HTTP.

What you'll learn

First, you'll learn how to create a reactive JAX-RS customer application by using the default reactive JAX-RS client APIs. You will and so learn how to take advantage of the RxJava reactive extensions with a pluggable reactive JAX-RS client provider that's published by Eclipse Bailiwick of jersey. The JAX-RS client is an API used to communicate with RESTful web services. The API makes information technology like shooting fish in a barrel to consume a spider web service past using the HTTP protocol, which means that you tin can efficiently implement client-side applications. The reactive client extension to JAX-RS is an API that enables yous to utilise the reactive programming model when using the JAX-RS client.

Reactive programming is an extension of asynchronous programming and focuses on the flow of data through data streams. Reactive applications process data when information technology becomes bachelor and respond to requests as soon as processing is consummate. The request to the application and response from the awarding are decoupled and then that the awarding is non blocked from responding to other requests in the meantime. Because reactive applications can run faster than synchronous applications, they provide a much smoother user experience.

The application in this guide demonstrates how the JAX-RS client accesses remote RESTful services by using asynchronous method calls. You'll first expect at the supplied client awarding that uses the JAX-RS default CompletionStage-based provider. Then, you'll alter the customer application to apply Jersey'south RxJava provider, which is an alternative JAX-RS reactive provider. Both Jersey and Apache CXF provide third-political party reactive libraries for RxJava and were tested for employ in Open up Freedom.

The application that you lot will exist working with consists of three microservices, organization, inventory, and query. Every 15 seconds, the system microservice calculates and publishes an event that contains its current average system load. The inventory microservice subscribes to that information so that it tin can keep an updated listing of all the systems and their current system loads.

Reactive Query Service

The microservice that you lot will modify is the query service. It communicates with the inventory service to decide which arrangement has the highest organization load and which arrangement has the everyman system load.

The system and inventory microservices use MicroProfile Reactive Messaging to send and receive the system load events. If you want to learn more about reactive messaging, see the Creating reactive Java microservices guide.

Boosted prerequisites

You need to have Docker installed. For installation instructions, refer to the official Docker documentation. You volition build and run the microservices in Docker containers. An installation of Apache Kafka is provided in another Docker container.

Getting started

The fastest way to piece of work through this guide is to clone the Git repository and use the projects that are provided inside:

                git clone https://github.com/openliberty/guide-reactive-remainder-customer.git cd guide-reactive-rest-customer              

The get-go directory contains the starting project that y'all volition build upon.

The cease directory contains the finished projection that you volition build.

Before yous begin, make sure you have all the necessary prerequisites.

Creating a web client using the default JAX-RS API

Navigate to the beginning directory to brainstorm.

JAX-RS provides a default reactive provider that you tin apply to create a reactive REST client using the CompletionStage interface.

Create an InventoryClient class, which retrieves inventory data, and a QueryResource form, which queries data from the inventory service.

                Create the                  InventoryClient                  interface.                query/src/main/java/io/openliberty/guides/query/client/InventoryClient.java              

InventoryClient.coffee

The getSystem() method returns the CompletionStage interface. This interface represents a unit or stage of a computation. When the associated ciphering completes, the value can exist retrieved. The rx() method calls the CompletionStage interface. It retrieves the CompletionStageRxInvoker course and allows these methods to function correctly with the CompletionStage interface return blazon.

                Create the                  QueryResource                  course.                query/src/main/coffee/io/openliberty/guides/query/QueryResource.java              

QueryResource.java

The systemLoad endpoint asynchronously processes the information that is retrieved by the InventoryClient interface and serves that data after all of the services respond. The thenAcceptAsync() and exceptionally() methods together bear like an asynchronous effort-grab block. The data is candy in the thenAcceptAsync() method only after the CompletionStage interface finishes retrieving it. When you return a CompletionStage type in the resource, it doesn't necessarily mean that the computation completed and the response was built.

A CountDownLatch object is used to track how many asynchronous requests are being waited on. After each thread is completed, the countdown() methodcounts the CountDownLatch object down towards 0. This means that the value returns only after the thread that's retrieving the value is complete.The await() method stops and waits until all of the requests are complete. While the countdown completes, the main thread is complimentary to perform other tasks. In this example, no such task is present.

Building and running the application

The arrangement, inventory, and query microservices will exist built in Docker containers. If you want to learn more near Docker containers, check out the Containerizing microservices guide.

Start your Docker environment.

To build the awarding, run the Maven install and package goals from the command-line session in the start directory:

                mvn -pl models install mvn package              

Run the following command to download or update to the latest Open Liberty Docker prototype:

                docker pull icr.io/appcafe/open-liberty:total-java11-openj9-ubi              

Run the following commands to containerize the microservices:

                docker build -t organisation:1.0-SNAPSHOT arrangement/. docker build -t inventory:1.0-SNAPSHOT inventory/. docker build -t query:1.0-SNAPSHOT query/.              

Next, use the provided script to start the application in Docker containers. The script creates a network for the containers to communicate with each other. Information technology creates containers for Kafka, Zookeeper, and all of the microservices in the projection.

                .\scripts\startContainers.bat              
                ./scripts/startContainers.sh              

The microservices volition take some time to become available. See the http://localhost:9085/wellness and http://localhost:9080/wellness URLs to ostend that the inventory and query microservices are up and running. One time the microservices are up and running, you can access the application past making requests to the query/systemLoad endpoint at the http://localhost:9080/query/systemLoad URL.

When the service is ready, you see an output similar to the post-obit instance. This example was formatted for readability:

                {     "highest": {         "hostname":"30bec2b63a96",         "systemLoad": 6.ane     },     "lowest": {         "hostname":"55ec2b63a96",         "systemLoad": 0.1     } }              

The JSON output contains a highest attribute that represents the system with the highest load. Similarly, the lowest attribute represents the system with the lowest load. The JSON output for each of these attributes contains the hostname and systemLoad of the organization.

When you are done checking out the awarding, run the following control to stop the query microservice. Leave the system and inventory services running because they will be used when the application is rebuilt later in the guide:

Updating the web client to use an alternative reactive provider

Although JAX-RS provides the default reactive provider that returns CompletionStage types, you tin alternatively employ some other provider that supports other reactive frameworks like RxJava. The Apache CXF and Eclipse Jersey projects produce such providers. You'll now update the web client to use the Jersey reactive provider for RxJava. With this updated reactive provider, you can write clients that use RxJava objects instead of clients that use only the CompletionStage interface. These custom objects provide a simpler and faster way for you lot to create scalable RESTful services with a CompletionStage interface.

                Supplant the Maven configuration file.                query/pom.xml              

pom.xml

                                                      1                  <?xml version='1.0' encoding='utf-8'?>                                      2                  <project                  xmlns=                    "                    http://maven.apache.org/POM/4.0.0                    "                                                        3                  xmlns:xsi=                    "                    http://world wide web.w3.org/2001/XMLSchema-instance                    "                                                        four                  xsi:schemaLocation=                    "                    http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-four.0.0.xsd                    "                                    >                                      5                  <modelVersion>4.0.0</modelVersion>                                      6                                      7                  <groupId>io.openliberty.guides</groupId>                                      eight                  <artifactId>query</artifactId>                                      9                  <version>one.0-SNAPSHOT</version>                                      10                  <packaging>war</packaging>                                      11                                      12                  <backdrop>                                      13                  <maven.compiler.source>1.8</maven.compiler.source>                                      14                  <maven.compiler.target>ane.8</maven.compiler.target>                                      15                  <projection.build.sourceEncoding>UTF-8</projection.build.sourceEncoding>                                      16                  <project.reporting.outputEncoding>UTF-eight</project.reporting.outputEncoding>                                      17                  <!-- Liberty configuration -->                                      18                  <freedom.var.default.http.port>9080</liberty.var.default.http.port>                                      19                  <freedom.var.default.https.port>9443</liberty.var.default.https.port>                                      xx                  </backdrop>                                      21                                      22                  <dependencies>                                      23                  <!-- Provided dependencies -->                                      24                  <dependency>                                      25                  <groupId>jakarta.platform</groupId>                                      26                  <artifactId>djakarta.jakartaee-api</artifactId>                                      27                  <version>8.0.0</version>                                      28                  <scope>provided</scope>                                      29                  </dependency>                                      30                  <dependency>                                      31                  <groupId>javax.enterprise.concurrent</groupId>                                      32                  <artifactId>javax.enterprise.concurrent-api</artifactId>                                      33                  <version>1.1</version>                                      34                  <scope>provided</telescopic>                                      35                  </dependency>                                      36                  <dependency>                                      37                  <groupId>javax.validation</groupId>                                      38                  <artifactId>validation-api</artifactId>                                      39                  <version>2.0.1.Final</version>                                      xl                  <telescopic>provided</scope>                                      41                  </dependency>                                      42                  <dependency>                                      43                  <groupId>org.eclipse.microprofile</groupId>                                      44                  <artifactId>microprofile</artifactId>                                      45                  <version>3.3</version>                                      46                  <type>pom</blazon>                                      47                  <scope>provided</scope>                                      48                  </dependency>                                      49                  <!-- Required dependencies -->                                      50                  <dependency>                                      51                  <groupId>io.openliberty.guides</groupId>                                      52                  <artifactId>models</artifactId>                                      53                  <version>i.0-SNAPSHOT</version>                                      54                  </dependency>                                      55                  <!-- Reactive dependencies -->                                      56                  <!-- tag::jerseyClient[] -->                                      57                  <dependency>                                      58                  <groupId>org.glassfish.jersey.core</groupId>                                      59                  <artifactId>jersey-client</artifactId>                                      60                  <version>2.35</version>                                      61                  </dependency>                                      62                  <!-- end::jerseyClient[] -->                                      63                  <!-- tag::jerseyRxjava[] -->                                      64                  <dependency>                                      65                  <groupId>org.glassfish.bailiwick of jersey.ext.rx</groupId>                                      66                  <artifactId>jersey-rx-customer-rxjava</artifactId>                                      67                  <version>2.35</version>                                      68                  </dependency>                                      69                  <!-- end::jerseyRxjava[] -->                                      70                  <!-- tag::jerseyRxjava2[] -->                                      71                  <dependency>                                      72                  <groupId>org.glassfish.bailiwick of jersey.ext.rx</groupId>                                      73                  <artifactId>bailiwick of jersey-rx-client-rxjava2</artifactId>                                      74                  <version>2.35</version>                                      75                  </dependency>                                      76                  <!-- stop::jerseyRxjava2[] -->                                      77                  <!-- For tests -->                                      78                  <dependency>                                      79                  <groupId>org.microshed</groupId>                                      80                  <artifactId>microshed-testing-liberty</artifactId>                                      81                  <version>0.9.one</version>                                      82                  <scope>test</scope>                                      83                  </dependency>                                      84                  <dependency>                                      85                  <groupId>org.testcontainers</groupId>                                      86                  <artifactId>mockserver</artifactId>                                      87                  <version>1.16.2</version>                                      88                  <scope>examination</scope>                                      89                  </dependency>                                      90                  <dependency>                                      91                  <groupId>org.mock-server</groupId>                                      92                  <artifactId>mockserver-client-java</artifactId>                                      93                  <version>5.11.2</version>                                      94                  <scope>test</scope>                                      95                  </dependency>                                      96                  <dependency>                                      97                  <groupId>org.junit.jupiter</groupId>                                      98                  <artifactId>junit-jupiter</artifactId>                                      99                  <version>5.8.1</version>                  100                  <scope>examination</scope>                  101                  </dependency>                  102                  </dependencies>                  103                  104                  <build>                  105                  <finalName>${project.artifactId}</finalName>                  106                  <plugins>                  107                  <plugin>                  108                  <groupId>org.apache.maven.plugins</groupId>                  109                  <artifactId>maven-war-plugin</artifactId>                  110                  <version>3.3.2</version>                  111                  <configuration>                  112                  <packagingExcludes>pom.xml</packagingExcludes>                  113                  </configuration>                  114                  </plugin>                  115                  116                  <!-- Liberty plugin -->                  117                  <plugin>                  118                  <groupId>io.openliberty.tools</groupId>                  119                  <artifactId>liberty-maven-plugin</artifactId>                  120                  <version>iii.5.i</version>                  121                  </plugin>                  122                  123                  <!-- Plugin to run unit tests -->                  124                  <plugin>                  125                  <groupId>org.apache.maven.plugins</groupId>                  126                  <artifactId>maven-surefire-plugin</artifactId>                  127                  <version>ii.22.2</version>                  128                  </plugin>                  129                  130                  <!-- Plugin to run integration tests -->                  131                  <plugin>                  132                  <groupId>org.apache.maven.plugins</groupId>                  133                  <artifactId>maven-failsafe-plugin</artifactId>                  134                  <version>2.22.two</version>                  135                  <executions>                  136                  <execution>                  137                  <id>integration-test</id>                  138                  <goals>                  139                  <goal>integration-test</goal>                  140                  </goals>                  141                  </execution>                  142                  <execution>                  143                  <id>verify</id>                  144                  <goals>                  145                  <goal>verify</goal>                  146                  </goals>                  147                  </execution>                  148                  </executions>                  149                  </plugin>                  150                  </plugins>                  151                  </build>                  152                  </project>                              

The jersey-rx-client-rxjava and jersey-rx-customer-rxjava2 dependencies provide the RxInvokerProvider classes, which are registered to the bailiwick of jersey-client ClientBuilder class.

Update the client to conform the custom object types that y'all are trying to return. You'll need to register the blazon of object that you want inside the client invocation.

                Supercede the                  InventoryClient                  interface.                query/src/primary/java/io/openliberty/guides/query/client/InventoryClient.coffee              

InventoryClient.java

The return blazon of the getSystem() method is now an Observable object instead of a CompletionStage interface. Observable is a collection of information that waits to be subscribed to earlier it tin release whatever data and is part of RxJava. The rx() method now needs to contain RxObservableInvoker.class as an statement. This argument calls the specific invoker, RxObservableInvoker, for the Observable class that'due south provided by Bailiwick of jersey. In the getSystem() method,the register(RxObservableInvokerProvider) method call registers the RxObservableInvoker class,which ways that the customer can recognize the invoker provider.

In some scenarios, a producer might generate more data than the consumers tin handle. JAX-RS can deal with cases similar these by using the RxJava Flowable class with backpressure. To learn more than about RxJava and backpressure, see JAX-RS reactive extensions with RxJava backpressure.

Updating the REST resource to support the reactive JAX-RS client

Now that the client methods return the Observable grade, you must update the resource to adjust these changes.

                Replace the                  QueryResource                  class.                query/src/main/java/io/openliberty/guides/query/QueryResource.java              

QueryResource.coffee

The goal of the systemLoad() method is to render the arrangement with the largest load and the organization with the smallest load. The systemLoad endpoint first gets all of the hostnames by calling the getSystems() method. So it loops through the hostnames and calls the getSystem() method on each i.

Instead of using the thenAcceptAsync() method, Appreciable uses the subscribe() method to asynchronously process data. Thus, whatsoever necessary data processing happens inside the subscribe() method. In this case, the necessary data processing is saving the data in the temporary Holder course. The Holder class is used to store the value that is returned from the client because values cannot be returned inside the subscribe() method. The highest and lowest load systems are updated in the updateValues() method.

Rebuilding and running the application

Run the Maven install and package goals from the control-line session in the showtime directory:

Run the post-obit command to containerize the query microservice:

                docker build -t query:i.0-SNAPSHOT query/.              

Next, use the provided script to restart the query service in a Docker container.

                .\scripts\startQueryContainer.bat              
                ./scripts/startQueryContainer.sh              

See the http://localhost:9080/health URL to ostend that the query microservice is up and running. Once the query microservice is up and running, you tin admission the application past making requests to the query/systemLoad endpoint at the http://localhost:9080/query/systemLoad URL.

Switching to a reactive programming model freed upward the thread that was handling your asking to query/systemLoad. While the client request is being handled, the thread can handle other piece of work.

When you are done checking out the awarding, run the following script to finish the application:

                .\scripts\stopContainers.bat              
                ./scripts/stopContainers.sh              

Testing the query microservice

A few tests are included for you to test the bones functionality of the query microservice. If a examination failure occurs, then you might have introduced a bug into the code.

                Create the                  QueryServiceIT                  class.                query/src/exam/java/it/io/openliberty/guides/query/QueryServiceIT.java              

QueryServiceIT.coffee

The testSystemLoad() test case verifies that the query service tin can correctly calculate the highest and lowest organisation loads.

Running the tests

Navigate to the query directory, then verify that the tests pass by running the Maven verify goal:

When the tests succeed, yous meet output similar to the following instance:

                  -------------------------------------------------------  T E S T S ------------------------------------------------------- Running it.io.openliberty.guides.query.QueryServiceIT Tests run: one, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: iii.88 s - in it.io.openliberty.guides.query.QueryServiceIT  Results:  Tests run: i, Failures: 0, Errors: 0, Skipped: 0                

Swell work! You're done!

You modified an application to make HTTP requests by using a reactive JAX-RS customer with Open Liberty and Jersey'southward RxJava provider.

Guide Attribution

Consuming RESTful services using the reactive JAX-RS client by Open up Liberty is licensed under CC BY-ND iv.0

How To Consuming Restful Web Service Using Jersey,

Source: https://openliberty.io/guides/reactive-rest-client.html

Posted by: buellthisced.blogspot.com

0 Response to "How To Consuming Restful Web Service Using Jersey"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel