Merge pull request #10452 from rozagerardo/rozagerardo/JAVA-4311_improve-spring-5-weblcient-article

[JAVA-4311] Improve "Spring Webclient" article
This commit is contained in:
Loredana Crusoveanu
2021-01-28 10:38:54 +02:00
committed by GitHub
5 changed files with 379 additions and 90 deletions
+9 -2
View File
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-5-reactive</artifactId>
<version>0.0.1-SNAPSHOT</version>
@@ -73,6 +74,12 @@
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring WebFlux WebSession -->
<dependency>
@@ -0,0 +1,24 @@
package com.baeldung.web.reactive.client;
public class Foo {
private String name;
public Foo() {
super();
}
public Foo(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -2,9 +2,10 @@ package com.baeldung.web.reactive.client;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration;
@SpringBootApplication
public class WebClientApplication{
@SpringBootApplication(exclude = { ReactiveSecurityAutoConfiguration.class })
public class WebClientApplication {
public static void main(String[] args) {
SpringApplication.run(WebClientApplication.class, args);
@@ -1,36 +1,18 @@
package com.baeldung.web.reactive.client;
import java.net.URI;
import java.nio.charset.Charset;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpOutputMessage;
import org.springframework.http.client.reactive.ClientHttpRequest;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;
@RestController
public class WebClientController {
@@ -43,74 +25,18 @@ public class WebClientController {
return response;
}
public void demonstrateWebClient() {
// request
WebClient.UriSpec<WebClient.RequestBodySpec> request1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST);
WebClient.UriSpec<WebClient.RequestBodySpec> request2 = createWebClientWithServerURLAndDefaultValues().post();
// request body specifications
WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST)
.uri("/resource");
WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post()
.uri(URI.create("/resource"));
// request header specification
WebClient.RequestHeadersSpec<?> requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class));
WebClient.RequestHeadersSpec<?> requestSpec2 = uri2.body(BodyInserters.fromValue("data"));
// inserters
BodyInserter<Publisher<String>, ReactiveHttpOutputMessage> inserter1 = BodyInserters.fromPublisher(Subscriber::onComplete, String.class);
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("key1", "value1");
map.add("key2", "value2");
BodyInserter<MultiValueMap<String, Object>, ClientHttpRequest> inserter2 = BodyInserters.fromMultipartData(map);
BodyInserter<Object, ReactiveHttpOutputMessage> inserter3 = BodyInserters.fromValue(new Object());
BodyInserter<String, ReactiveHttpOutputMessage> inserter4 = BodyInserters.fromValue("body");
// responses
WebClient.ResponseSpec response1 = uri1.body(inserter3)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
.acceptCharset(Charset.forName("UTF-8"))
.ifNoneMatch("*")
.ifModifiedSince(ZonedDateTime.now())
.retrieve();
String response2 = uri1.exchangeToMono(response -> response.bodyToMono(String.class))
.block();
String response3 = uri2.retrieve()
.bodyToMono(String.class)
.block();
WebClient.ResponseSpec response4 = requestSpec2.retrieve();
@PostMapping("/resource")
public Mono<String> postStringResource(@RequestBody Mono<String> bodyString) {
return bodyString.map(body -> "processed-" + body);
}
private WebClient createWebClient() {
return WebClient.create();
@PostMapping("/resource-foo")
public Mono<String> postFooResource(@RequestBody Mono<Foo> bodyFoo) {
return bodyFoo.map(foo -> "processedFoo-" + foo.getName());
}
private WebClient createWebClientWithServerURL() {
return WebClient.create("http://localhost:8081");
@PostMapping(value = "/resource-multipart", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String handleFormUpload(@RequestPart("key1") String value1, @RequestPart("key2") String value2) {
return "processed-" + value1 + "-" + value2;
}
private WebClient createWebClientConfiguringTimeout() {
HttpClient httpClient = HttpClient.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
.doOnConnected(conn -> conn.addHandlerLast(new ReadTimeoutHandler(5000, TimeUnit.MILLISECONDS))
.addHandlerLast(new WriteTimeoutHandler(5000, TimeUnit.MILLISECONDS)));
return WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();
}
private WebClient createWebClientWithServerURLAndDefaultValues() {
return WebClient.builder()
.baseUrl("http://localhost:8081")
.defaultCookie("cookieKey", "cookieValue")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080"))
.build();
}
}