SpringBoot中的響應(yīng)式web應(yīng)用詳解
簡介
在Spring 5中,Spring MVC引入了webFlux的概念,webFlux的底層是基于reactor-netty來的,而reactor-netty又使用了Reactor庫。
本文將會(huì)介紹在Spring Boot中reactive在WebFlux中的使用。
Reactive in Spring
前面我們講到了,webFlux的基礎(chǔ)是Reactor。 于是Spring Boot其實(shí)擁有了兩套不同的web框架,第一套框架是基于傳統(tǒng)的Servlet API和Spring MVC,第二套是基于最新的reactive框架,包括 Spring WebFlux 和Spring Data的reactive repositories。

我們用上面的一張圖可以清晰的看到兩套體系的不同。
對于底層的數(shù)據(jù)源來說,MongoDB, Redis, 和 Cassandra 可以直接以reactive的方式支持Spring Data。而其他很多關(guān)系型數(shù)據(jù)庫比如Postgres, Microsoft SQL Server, MySQL, H2 和 Google Spanner 則可以通過使用R2DBC 來實(shí)現(xiàn)對reactive的支持。
而Spring Cloud Stream甚至可以支持RabbitMQ和Kafka的reactive模型。
下面我們將會(huì)介紹一個(gè)具體的Spring Boot中使用Spring WebFlux的例子,希望大家能夠喜歡。
注解方式使用WebFlux
要使用Spring WebFlux,我們需要添加如下的依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
只用注解的方式和普通的Spring MVC的方式很類似,我們可以使用@RestController表示是一個(gè)rest服務(wù),可以使用 @GetMapping('/hello') 來表示一個(gè)get請求。
不同之處在于,我們請求的產(chǎn)生方式和返回值。
熟悉Reactor的朋友可能都知道,在Reactor中有兩種產(chǎn)生序列的方式,一種是Flux一種是Mono,其中Flux表示1或者多,而Mono表示0或者1。
看一下我們的Controller該怎么寫:
@RestControllerpublic class WelcomeController { @GetMapping('/hello') public Mono<String> hello() { return Mono.just('www.flydean.com'); } @GetMapping('/hellos') public Flux<String> getAll() { //使用lambda表達(dá)式 return Flux.fromStream(Stream.of('www.flydean.com','flydean').map(String::toLowerCase)); }}
這個(gè)例子中,我們提供了兩個(gè)get方法,第一個(gè)是hello,直接使用Mono.just返回一個(gè)Mono。
第二個(gè)方法是hellos,通過Flux的一系列操作,最后返回一個(gè)Flux對象。
有了Mono對象,我們怎么取出里面的數(shù)據(jù)呢?
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的結(jié)果,通過exchange將其轉(zhuǎn)換為ClientResponse。
然后提供了一個(gè)getResult方法從result中獲取最終的返回結(jié)果。
這里,我們先調(diào)用FlatMap對ClientResponse進(jìn)行轉(zhuǎn)換,然后再調(diào)用block方法,產(chǎn)生一個(gè)新的subscription。
最后,我們看一下Spring Boot的啟動(dòng)類:
@Slf4j@SpringBootApplicationpublic 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
剛剛的注解方式其實(shí)跟我們常用的Spring MVC基本上是一樣的。
接下來,我們看一下,如果是以編程的方式來編寫上面的邏輯應(yīng)該怎么處理。
首先,我們定義一個(gè)處理hello請求的處理器:
@Componentpublic class WelcomeHandler {public Mono<ServerResponse> hello(ServerRequest request) {return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN).body(BodyInserters.fromValue('www.flydean.com!'));}}
和普通的處理一樣,我們需要返回一個(gè)Mono對象。
注意,這里是ServerRequest,因?yàn)閃ebFlux中沒有Servlet。
有了處理器,我們需要寫一個(gè)Router來配置路由:
@Configurationpublic class WelcomeRouter {@Beanpublic RouterFunction<ServerResponse> route(WelcomeHandler welcomeHandler) {return RouterFunctions.route(RequestPredicates.GET('/hello').and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), welcomeHandler::hello);}}
上面的代碼將/hello和welcomeHandler::hello進(jìn)行了綁定。
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代碼進(jìn)行測試呢?
本質(zhì)上是和WelcomeWebClient的實(shí)現(xiàn)是一樣的,我們?nèi)フ埱髮?yīng)的對象,然后檢測其返回值,最后判斷返回值是否我們所期待的內(nèi)容。
如下所示:
@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!'); }}
總結(jié)
webFlux使用了Reactor作為底層的實(shí)現(xiàn),和通常我們習(xí)慣的web請求方式是有很大不同的,但是通過我們的Spring框架,可以盡量保證原有的代碼編寫風(fēng)格和習(xí)慣。
只需要在個(gè)別部分做微調(diào)。希望大家能夠通過這個(gè)簡單的例子,熟悉Reactive的基本編碼實(shí)現(xiàn)。
本文的例子可以參考:springboot-reactive-web
到此這篇關(guān)于SpringBoot中的響應(yīng)式web應(yīng)用詳解的文章就介紹到這了,更多相關(guān)SpringBoot響應(yīng)式web應(yīng)用內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Android table布局開發(fā)實(shí)現(xiàn)簡單計(jì)算器2. 理解PHP5中static和const關(guān)鍵字3. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼4. php模擬實(shí)現(xiàn)斗地主發(fā)牌5. IntelliJ IDEA安裝插件的方法步驟6. phpstorm恢復(fù)默認(rèn)設(shè)置的方法步驟7. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. Python random庫使用方法及異常處理方案9. Vuex localStorage的具體使用10. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟

網(wǎng)公網(wǎng)安備