天天看點

SpringBoot中的響應式web應用簡介Reactive in Spring注解方式使用WebFlux程式設計方式使用webFluxSpring WebFlux的測試總結

簡介

在Spring 5中,Spring MVC引入了webFlux的概念,webFlux的底層是基于reactor-netty來的,而reactor-netty又使用了Reactor庫。

本文将會介紹在Spring Boot中reactive在WebFlux中的使用。

Reactive in Spring

前面我們講到了,webFlux的基礎是Reactor。 于是Spring Boot其實擁有了兩套不同的web架構,第一套架構是基于傳統的Servlet API和Spring MVC,第二套是基于最新的reactive架構,包括 Spring WebFlux 和Spring Data的reactive repositories。

SpringBoot中的響應式web應用簡介Reactive in Spring注解方式使用WebFlux程式設計方式使用webFluxSpring WebFlux的測試總結

我們用上面的一張圖可以清晰的看到兩套體系的不同。

對于底層的資料源來說,MongoDB, Redis, 和 Cassandra 可以直接以reactive的方式支援Spring Data。而其他很多關系型資料庫比如Postgres, Microsoft SQL Server, MySQL, H2 和 Google Spanner 則可以通過使用R2DBC 來實作對reactive的支援。

而Spring Cloud Stream甚至可以支援RabbitMQ和Kafka的reactive模型。

下面我們将會介紹一個具體的Spring Boot中使用Spring WebFlux的例子,希望大家能夠喜歡。

注解方式使用WebFlux

要使用Spring WebFlux,我們需要添加如下的依賴:

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

隻用注解的方式和普通的Spring MVC的方式很類似,我們可以使用@RestController表示是一個rest服務,可以使用 @GetMapping("/hello") 來表示一個get請求。

不同之處在于,我們請求的産生方式和傳回值。

熟悉Reactor的朋友可能都知道,在Reactor中有兩種産生序列的方式,一種是Flux一種是Mono,其中Flux表示1或者多,而Mono表示0或者1。

看一下我們的Controller該怎麼寫:

@RestController
public class WelcomeController {

    @GetMapping("/hello")
    public Mono<String> hello() {
        return Mono.just("www.flydean.com");
    }

    @GetMapping("/hellos")
    public Flux<String> getAll() {
        //使用lambda表達式
        return Flux.fromStream(Stream.of("www.flydean.com","flydean").map(String::toLowerCase));
    }

}           

這個例子中,我們提供了兩個get方法,第一個是hello,直接使用Mono.just傳回一個Mono。

第二個方法是hellos,通過Flux的一系列操作,最後傳回一個Flux對象。

有了Mono對象,我們怎麼取出裡面的資料呢?

public class WelcomeWebClient {
    private WebClient client = WebClient.create("http://localhost:8080");

    private final Mono<ClientResponse> result = client.get()
            .uri("/hello")
            .accept(MediaType.TEXT_PLAIN)
            .exchange();

    public String getResult() {
        return " result = " + result.flatMap(res -> res.bodyToMono(String.class)).block();
    }
}           

我們通過WebClient來擷取get的結果,通過exchange将其轉換為ClientResponse。

然後提供了一個getResult方法從result中擷取最終的傳回結果。

這裡,我們先調用FlatMap對ClientResponse進行轉換,然後再調用block方法,産生一個新的subscription。

最後,我們看一下Spring Boot的啟動類:

@Slf4j
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

        WelcomeWebClient welcomeWebClient = new WelcomeWebClient();
        log.info("react result is {}",welcomeWebClient.getResult());
    }
}           

程式設計方式使用webFlux

剛剛的注解方式其實跟我們常用的Spring MVC基本上是一樣的。

接下來,我們看一下,如果是以程式設計的方式來編寫上面的邏輯應該怎麼處理。

首先,我們定義一個處理hello請求的處理器:

@Component
public class WelcomeHandler {

    public Mono<ServerResponse> hello(ServerRequest request) {
        return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
            .body(BodyInserters.fromValue("www.flydean.com!"));
    }
}           

和普通的處理一樣,我們需要傳回一個Mono對象。

注意,這裡是ServerRequest,因為WebFlux中沒有Servlet。

有了處理器,我們需要寫一個Router來配置路由:

@Configuration
public class WelcomeRouter {

    @Bean
    public RouterFunction<ServerResponse> route(WelcomeHandler welcomeHandler) {

        return RouterFunctions
            .route(RequestPredicates.GET("/hello").
                    and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), welcomeHandler::hello);
    }
}           

上面的代碼将/hello和welcomeHandler::hello進行了綁定。

WelcomeWebClient和Application是和第一種方式是一樣的。

public class WelcomeWebClient {
    private WebClient client = WebClient.create("http://localhost:8080");

    private Mono<ClientResponse> result = client.get()
            .uri("/hello")
            .accept(MediaType.TEXT_PLAIN)
            .exchange();

    public String getResult() {
        return " result = " + result.flatMap(res -> res.bodyToMono(String.class)).block();
    }
}           
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

        WelcomeWebClient welcomeWebClient = new WelcomeWebClient();
        log.info("react result is {}",welcomeWebClient.getResult());
    }
}           

Spring WebFlux的測試

怎麼對webFlux代碼進行測試呢?

本質上是和WelcomeWebClient的實作是一樣的,我們去請求對應的對象,然後檢測其傳回值,最後判斷傳回值是否我們所期待的内容。

如下所示:

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WelcomeRouterTest {
    @Autowired
    private WebTestClient webTestClient;

    @Test
    public void testHello() {
        webTestClient
                .get().uri("/hello")
                .accept(MediaType.TEXT_PLAIN)
                .exchange()
                .expectStatus().isOk()
                .expectBody(String.class).isEqualTo("www.flydean.com!");
    }
}           

總結

webFlux使用了Reactor作為底層的實作,和通常我們習慣的web請求方式是有很大不同的,但是通過我們的Spring架構,可以盡量保證原有的代碼編寫風格和習慣。

隻需要在個别部分做微調。希望大家能夠通過這個簡單的例子,熟悉Reactive的基本編碼實作。

本文的例子可以參考:

springboot-reactive-web

本文作者:flydean程式那些事

本文連結:

http://www.flydean.com/springboot-reactive-web/

本文來源:flydean的部落格

歡迎關注我的公衆号:「程式那些事」最通俗的解讀,最深刻的幹貨,最簡潔的教程,衆多你不知道的小技巧等你來發現!