前面介绍了Spring Boot使用Spring MVC模式搭建一个简单的WebFlux项目,本节为大家介绍Spring Boot提供的另一种模式—— Spring WebFlux。引用Spring官网的说明,我们在第1章已经看到过.
WebFlux是一个非阻塞的Web框架,它不再完全依赖于Servlet,而是实现了Reactive Streams规范。也就是说,可以使用响应式编程,但是并非无法运行在之前的Servlet容器上,只不过必须是在Servlet 3.1以上,并且默认推荐的是使用Netty这种异步容器。刚才我们提到了响应式编程,接下来利用响应式编程来创建一个Spring Boot WebFlux项目。
添加WebFlux依赖
首先创建一个项目,在项目的pom文件中添加WebFlux依赖。Spring WebFlux同样支持传统Spring MVC使用注解的形式进行WebFlux跳转,同时支持函数式编程配置路由进行WebFlux跳转。传统模式就不再赘述了,这里以响应式编程为例,Spring WebFlux依赖的内容如代码
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
创建一个处理方法类
新建类HelloHandle,创建一个hello方法供接下来使用,其中返回值Mono<ServerResponse>作为响应对象,其中ServerResponse包含响应状态、响应头信息等,类上面的@Component注解用于将类实例化到Spring容器中。总的来说,这个方法就是返回一句字符串,HelloHandle类的内容如代码
package com.shrimpking;
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;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/12/20 21:52
*/
@Component
public class HelloHandler
{
public Mono<ServerResponse> hello(ServerRequest request){
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject("Hello,this is a springboot webflux project"));
}
}
创建一个Router类
创建一个HelloRouter类,用来定义路由信息,每个路由都会映射到对应的处理方法(功能类似于@RequestMapping)。当接收到对应HTTP请求后,调用此方法,通过RouterFunctions.route(RequestPredicate, HandlerFunction)提供一个路由器函数的默认实现,HelloRouter的内容如代码
package com.shrimpking;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/12/20 21:55
*/
@Configuration
public class HelloRouter
{
@Bean
public RouterFunction<ServerResponse> routeHello(HelloHandler helloHandler){
return RouterFunctions
.route(RequestPredicates.GET("/hello")
.and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
helloHandler::hello);
}
}
测试运行
启动项目,我们来观察一下控制台,可以从第4行看到,刚刚写的hello映射已经成功了。正如之前介绍的,默认启用的Netty容器运行端口默认为8080。在浏览器上访问http://localhost:8080/hello可以看到:
响应式编程的简单实现到这里就结束了,可能在工作和学习上两种方式有不同的使用情况,无论是响应式编程还是非响应式编程,都有各自不同的好处,这里不做更多的比较了,具体可以按照自己的实际需求来选择。