本文只是简单使用SpringBoot2使用WebFlux的函数式编程简单使用,后续会继续写关于Webflux相关的文章。
最近一直在研究WebFlux,后续会陆续出一些相关的文章。
首先看一下Srping官网上的一张图,对比一下SpringMvc和Spring WebFlux,如图:
image
在查看一下WebFlux的官方文档:https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#spring-webflux,WebFlux提供了函数式编程,本文简单介绍一下WebFlux函数式编程简单使用。
新建项目创建一个项目,pom文件中引入webflux依赖,完整pom文件如下:
4.0.0 com.dalaoyang springboot2_webflux0.0.1-SNAPSHOT jar springboot2_webflux springboot2_webflux org.springframework.boot spring-boot-starter-parent2.0.3.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starterorg.springframework.boot spring-boot-starter-testtest org.springframework.boot spring-boot-starter-webfluxorg.springframework.boot spring-boot-maven-plugin
首先试试引入WebFlux依赖之后,SpringMvc方式是否还能使用,新建一个HelloController,完整代码如下,执行后发现,是可以正常执行访问的,这其实就是我们所说的注解式编程。
package com.dalaoyang.controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class HelloController { @GetMapping("hello") public String Hello(){ return "Hello this is SpringWebFlux";
}
}结果如图:
image
接下来使用函数式编程,首先查阅一下官方文档,如图:
image
我们需要创建一个HandlerFunction返回值为Mono,新建一个HiHandler,里面写一个方法Hi,完整代码如下:
package com.dalaoyang.handler;import org.springframework.http.MediaType;import org.springframework.stereotype.Component;import org.springframework.web.reactive.function.BodyInserters;import org.springframework.web.reactive.function.server.ServerRequest;import org.springframework.web.reactive.function.server.ServerResponse;import reactor.core.publisher.Mono;@Componentpublic class HiHandler { public Mono Hi(ServerRequest request) { return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject("Hi , this is SpringWebFlux"));
}
}
作者:dalaoyang
链接:https://www.jianshu.com/p/55c1a84bd145



