Zachary Palmer

Zachary Palmer

1567494324

Reactive Programming in Java: Using the WebClient Class

Originally published at http://www.profesor-p.com

In this article, we will talk about the WebClient class found in the Spring Boot framework. You can access the source code for this article here

This class would be the equivalent of the RestTemplate class, but it works with asynchronous requests.

If you want to use this class, you should put these dependencies in your Maven file.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

This is also why you need to use WebFlux, which is available in version 5 of Spring. Remember that this version of Spring requires Java 8 or higher.

With WebFlux, which is based on Project Reactor, you can write reactive applications. This kind of application is characterized because the requests aren't blocking and functional programming is widely used.

If you want to understand this article, you need basic prior knowledge about the Reactor and the Mono class. Although, if you have used Streams in Java, you may think that a Mono object is like a Stream that can emit a value or an error.

But I am not going to delve into these issues because they are beyond the scope of this article. It would be sufficient to say that when using the WebClient class, you can make several calls in parallel, so if each request is answered in 2 seconds and you make 5 calls, you can get all the answers in just over 2 seconds, instead of 10.

Parallel Request

In this example project, I have written a server and a client. The server will be running in the 8081 port, and the client will listen in the 8080 port.

This is the code that executes the server application.

@SpringBootApplication
public class WebServerApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(WebServerApplication.class).
properties(Collections.singletonMap("server.port", "8081")).run(args);
}
}

If you make a request to http://localhost:8080/client/XXX, the function testGet will be executed.

@RestController()
@RequestMapping("/client")
@Slf4j
public class ClientController {
final String urlServer="http://localhost:8081";
@GetMapping("/{param}")
public Mono<ResponseEntity<Mono<String>>> testGet(@PathVariable String param) {
final long dateStarted = System.currentTimeMillis();
WebClient webClient = WebClient.create(urlServer+"/server/");
Mono<ClientResponse> respuesta = webClient.get().uri("?queryParam={name}", param).exchange();
Mono<ClientResponse> respuesta1 = webClient.get().uri("?queryParam={name}","SPEED".equals(param)?"SPEED":"STOP").exchange();
Mono<ResponseEntity<Mono<String>>> f1 = Mono.zip(respuesta, respuesta1)
.map(t -> {
if (!t.getT1().statusCode().is2xxSuccessful()) {
return ResponseEntity.status(t.getT1().statusCode()).body(t.getT1().bodyToMono(String.class));
}
if (!t.getT2().statusCode().is2xxSuccessful()) {
return ResponseEntity.status(t.getT2().statusCode()).body(t.getT2().bodyToMono(String.class));
}
return ResponseEntity.ok().body(Mono.just(
"All OK. Seconds elapsed: " + (((double) (System.currentTimeMillis() - dateStarted) / 1000))));
});
return f1;
}

This is a simple controller that performs two requests to the URL http://localhost:8081. In the first request, the parameter passed is the function received in the param variable. In the second, the sentence "STOP" is sent if the param variable is different from the word SPEED.

The server upon receiving the parameter "STOP" will wait 5 seconds and then will answer.

From the moment we create the instance of the class WebClient, I specify the URL of the request.

WebClient webClient = WebClient.create(urlServer+"/server/");

Then, it executes the call of the type GET to the server passing the parameter QueryParam. In the end, when executing the function exchange, it will receive a Mono object containing a ClientResponse class that is equivalent to the ResponseEntity object of the RestTemplate class. The class ClientResponse will have the HTTP code, the body, and the headers sent by the server.

Mono<ClientResponse> respuesta = webClient.get().uri("?queryParam={name}", param).exchange();

Wait a minute...

Did I say it will execute? Well, I lied. Really only what I want to do has been declared. In reactive programming, until someone does not subscribe to a request, nothing is executed, so the request to the server has not yet been made.

On the next line, the second request to the server is defined.

Mono<ClientResponse> respuesta1 = webClient.get()
  .uri("?queryParam={name}","SPEED".equals(param)?"SPEED":"STOP").exchange();

Finally, a Mono object is created, which will be the result of the previous two, using the zip function.

Using the map function, a ResponseEntity object with the HTTP code equal to OK will be returned if the two requests have answered a 2XX code; otherwise, the code and answer of the server will be returned.

Being WebClient-reactive, the two requests are realized simultaneously, and therefore, you will be able to see that if you execute this code: curl http://localhost:8080/client/STOP, you have the answer in just over 5 seconds, even if the sum of the call time is greater than 10 seconds.

All OK. Seconds elapsed: 5.092

A POST request

In the testURLs function, there is an example of a call using POST.

This function receives a Map in the body that will then be placed in the request headers. In addition, this map will be sent in the body of the request that will be made to the server.

@PostMapping("")
public Mono<String> testURLs(@RequestBody Map<String,String> body,
@RequestParam(required = false) String url) {
log.debug("Client: in testURLs");
WebClient.Builder builder = WebClient.builder().baseUrl(urlServer).
defaultHeader(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON_VALUE);
if (body!=null && body.size()>0 )
{
for (Map.Entry<String, String> map : body.entrySet() )
{
builder.defaultHeader(map.getKey(), map.getValue());
}
}
WebClient webClient = builder.build();
String urlFinal;
if (url==null)
urlFinal="/server/post";
else
urlFinal="/server/"+url;
Mono<String> respuesta1 = webClient.post().uri(urlFinal).body(BodyInserters.fromObject(body)).exchange()
.flatMap( x -> 
{ 
if ( ! x.statusCode().is2xxSuccessful())
return Mono.just("LLamada a "+urlServer+urlFinal+" Error 4xx: "+x.statusCode()+"\n");
return x.bodyToMono(String.class);
});    
return respuesta1;
}

To insert the body of the message, the auxiliary class BodyInserters will be used. If the message were on the object Mono, this code could be used:

BodyInserters.fromPublisher(Mono.just(MONO_OBJECT),String.class);

When performing a flatMap, the output of the ClientResponse object will be captured and a Mono object will be returned with the string to be returned.

The flatMap function will flatten that Mono object and extract the string inside it, and that is why a Mono <String> will be received and not a Mono <Mono <String>>. However, it would happen if we used the function map.

Making the following call:

curl  -s -XPOST http://localhost:8080/client  -H 'Content-Type: application/json' -d'{"aa": "bbd"}'

The following output will be obtained:

the server said: {aa=bbd}
Headers: content-length:12
Headers: aa:bbd
Headers: accept-encoding:gzip
Headers: Content-Type:application/json
Headers: accept:*/*
Headers: user-agent:ReactorNetty/0.9.0.M3
Headers: host:localhost:8081

This output is produced by the function postExamle of the server

@PostMapping("post")
public ResponseEntity<String> postExample(@RequestBody Map<String,String> body,ServerHttpRequest  request) {
String s="the server said: "+body+"\n";
for (Entry<String, List<String>> map : request.getHeaders().entrySet())
{
s+="Headers: "+map.getKey()+ ":"+map.getValue().get(0)+"\n";
}
return ResponseEntity.ok().body(s);
}

Note that when using the WebFlux library that is not fully compatible with javax.servlet, we must receive a ServerHttpRequest object to collect all raw headers. The equivalent in a non-reactive application would be an HttpServletRequest object.

If you execute the sentence:

curl  -s -XPOST http://localhost:8080/client?url=aa  -H 'Content-Type: application/json' -d'{"aa": "bbd"}'

The client will try to call http://localhost:8081/server/aa, which will cause an error, and the following will be received.

http://localhost:8081/server/aa Called. Error 4xx: 404 NOT_FOUND

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Java Programming Masterclass for Software Developers

Selenium WebDriver with Java -Basics to Advanced+Frameworks

Java In-Depth: Become a Complete Java Engineer!

Top 4 Spring Annotations for Java Developer in 2019

Java Tutorial for Absolute Beginners

100+ Java Interview Questions and Answers In 2019

Python vs Java: Understand Object Oriented Programming

Angular 7 + Spring Boot CRUD Example

#java #web-service #spring-boot

What is GEEK

Buddha Community

Reactive Programming in Java: Using the WebClient Class
Tyrique  Littel

Tyrique Littel

1600135200

How to Install OpenJDK 11 on CentOS 8

What is OpenJDK?

OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE). It contains the virtual machine, the Java Class Library, and the Java compiler. The difference between the Oracle OpenJDK and Oracle JDK is that OpenJDK is a source code reference point for the open-source model. Simultaneously, the Oracle JDK is a continuation or advanced model of the OpenJDK, which is not open source and requires a license to use.

In this article, we will be installing OpenJDK on Centos 8.

#tutorials #alternatives #centos #centos 8 #configuration #dnf #frameworks #java #java development kit #java ee #java environment variables #java framework #java jdk #java jre #java platform #java sdk #java se #jdk #jre #open java development kit #open source #openjdk #openjdk 11 #openjdk 8 #openjdk runtime environment

Samanta  Moore

Samanta Moore

1620458875

Going Beyond Java 8: Local Variable Type Inference (var) - DZone Java

According to some surveys, such as JetBrains’s great survey, Java 8 is currently the most used version of Java, despite being a 2014 release.

What you are reading is one in a series of articles titled ‘Going beyond Java 8,’ inspired by the contents of my book, Java for Aliens. These articles will guide you step-by-step through the most important features introduced to the language, starting from version 9. The aim is to make you aware of how important it is to move forward from Java 8, explaining the enormous advantages that the latest versions of the language offer.

In this article, we will talk about the most important new feature introduced with Java 10. Officially called local variable type inference, this feature is better known as the **introduction of the word **var. Despite the complicated name, it is actually quite a simple feature to use. However, some observations need to be made before we can see the impact that the introduction of the word var has on other pre-existing characteristics.

#java #java 11 #java 10 #java 12 #var #java 14 #java 13 #java 15 #verbosity

Samanta  Moore

Samanta Moore

1623803640

Top Tips for Learning Java Programming

If you’re here for the top tips, we assume you’re ahead of the “how to learn Java” part and already boarded on your flight of learning Java. In this lesson, apart from just throwing some do’s and don’ts, we’ll be asking some basic questions that will help you align your path with what’s best for you.

Are you following a plan?

Determining your goal and creating a learning strategy is more significant than you can probably think of. Your ambition, execution, and consistency can make or break your career. So if you want to become a full-time Java Developer shadowing a layout/map goes without saying.

Are you a master of the basics?

Mastering the basics doesn’t necessarily mean learning syntax by heart and not be able to do anything with it. It actually means you’re comfortable working with keywords, know the language protocols, smartly use variables and loops. Know how to choose a data structure depending upon a certain problem. Able to implement object orient approach, since Java is an object-oriented language. Understand encapsulation and how to tamper with it. With this much content freely available widely on the web, newbies are most likely to fell prey to learn more in a shorter period of time. However, you need to understand you can’t build a sustainable building over a weak foundation. Hence, it’s forever helpful to give due time to all the concepts in order to truly “master” them.

#java #learning java programming #java programming #top tips #top tips for learning java programming #programmers

Samanta  Moore

Samanta Moore

1620462686

Spring Boot and Java 16 Records

In this article, we will discuss Java 16’s newest feature, Records. Then we will apply this knowledge and use it in conjunction with a Spring Boot application.

On March 16th, 2021, Java 16 was GA. With this new release, tons of new exciting features have been added. Check out the release notes to know more about these changes in detail. This article’s focus will be on Java Records, which got delivered with JEP 395. Records were first introduced in JDK 14 as a preview feature proposed by JEP 359, and with JDK 15, they remained in preview with JEP 384. However, with JDK 16, Records are no longer in preview.

I have picked Records because they are definitely the most favored feature added in Java 16, according to this Twitter poll by Java Champion Mala Gupta.

I also conducted a similar survey, but it was focused on features from Java 8 onwards. The results were not unexpected, as Java 8 is still widely used. Very unfortunate, though, as tons of new features and improvements are added to newer Java versions. But in terms of features, Java 8 was definitely a game-changer from a developer perspective.

So let’s discuss what the fuss is about Java Records.

#java #springboot #java programming #records #java tutorials #java programmer #java records #java 16

How To Avoid Blocking in Reactive Java

Good practices in asynchronous programming

The key to reactive programming is to react. You don’t say “do this now,” you say “do this when.” The “when” applies to when you have work to do. The work comes to you as events: a message on a message bus or an HTTP request.

First, I should explain the reason reactive programming is important. One of the benefits of Java is relatively easy threading. That has made threads the predominant model for handling events. When you get an event, you dispatch a thread to handle it. The problem is when you get a lot of events, you wind up creating a lot of threads. Threads can be expensive; each one has stack memory and switching threads requires a system call and context switch.

The Node.js system only had a single thread when it was created. (It introduced worker threads in v10.5.0). And yet it became a very popular system for building servers that could handle thousands of requests. It does this by using an event-driven idiom for handling requests. Because it only had a single thread, most libraries that implement things like HTTP servers or clients, database clients, or other I/O intensive libraries had to use the single event loop of the single thread.

But Java used the thread-per-request, which has become a bottleneck in scaling. Languages like Scala, so named because it could be more scalable, were created with extensive frameworks to enable event-driven or asynchronous I/O. Java 8 introduced CompletableFuture. Java 9 introduced the Flow class with its Publisher and Subscriber. These are used as the basis for the two fully reactive frameworks, RxJava and Project Reactor.

Because Java has used the thread-per-request model for so long, most libraries that deal with I/O will block. They can block because they expect to own the thread they’re running on and won’t block other requests. But now that we can use the asynchronous model, they become a problem. And because Java now has a hybrid model, it’s hard to tell when and how you should use threads when in a mostly asynchronous system.

#java #programming #software-engineering #reactive-programming #software-development #how to avoid blocking in reactive java