SpringBoot2 WebFlux函数式编程简介
本文将简要展示如何在SpringBoot2环境下运用WebFlux的函数式编程特性,后续还将推出更多关于WebFlux的深度内容。
近期笔者专注于WebFlux的研究,计划陆续分享相关技术文章。
首先参考Spring官网提供的一张对比图,直观比较SpringMvc与Spring WebFlux的区别,如图所示:

查阅WebFlux官方文档(https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html)可知,WebFlux支持函数式编程风格,下文将简述其基本用法。
新建项目
创建一个新项目,并在pom.xml文件中添加webflux依赖,完整的pom配置如下:
<?xml version="1.0" encoding="UTF-8"?>
4.0.0
com.dalaoyang
springboot2_webflux
0.0.1-SNAPSHOT
jar
springboot2_webflux
springboot2_webflux
org.springframework.boot
spring-boot-starter-parent
2.0.3.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-webflux
org.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;
/**
* @author dalaoyang
* @project springboot_learn
* @package com.dalaoyang.controller
* @email yangyang@dalaoyang.cn
* @date 2026/7/30
*/
@RestController
public class HelloController {
@GetMapping("hello")
public String Hello(){
return "Hello this is SpringWebFlux";
}
}
运行结果如图所示:

随后转向函数式编程的实现,先查阅官方文档说明,如图所示:

我们需要定义一个返回值为Mono的HandlerFunction接口实现。新建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;
/**
* @author dalaoyang
* @project springboot_learn
* @package com.dalaoyang.handler
* @email yangyang@dalaoyang.cn
* @date 2026/7/30
*/
@Component
public class HiHandler {
public Mono Hi(ServerRequest request) {
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject("Hi , this is SpringWebFlux"));
}
}
ServerResponse用于封装响应数据,其源码展示了包含响应状态、响应头等属性,部分代码如下:
package org.springframework.web.reactive.function.server;
import java.net.URI;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import org.reactivestreams.Publisher;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseCookie;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
public interface ServerResponse {
HttpStatus statusCode();
HttpHeaders headers();
MultiValueMap cookies();
Mono writeTo(ServerWebExchange var1, ServerResponse.Context var2);
static ServerResponse.BodyBuilder from(ServerResponse other) {
return new DefaultServerResponseBuilder(other);
}
static ServerResponse.BodyBuilder status(HttpStatus status) {
return new DefaultServerResponseBuilder(status);
}
static ServerResponse.BodyBuilder status(int status) {
return new DefaultServerResponseBuilder(status);
}
static ServerResponse.BodyBuilder ok() {
return status(HttpStatus.OK);
}
static ServerResponse.BodyBuilder created(URI location) {
ServerResponse.BodyBuilder builder = status(HttpStatus.CREATED);
return (ServerResponse.BodyBuilder)builder.location(location);
}
static ServerResponse.BodyBuilder accepted() {
return status(HttpStatus.ACCEPTED);
}
static ServerResponse.HeadersBuilder<?> noContent() {
return status(HttpStatus.NO_CONTENT);
}
static ServerResponse.BodyBuilder seeOther(URI location) {
ServerResponse.BodyBuilder builder = status(HttpStatus.SEE_OTHER);
return (ServerResponse.BodyBuilder)builder.location(location);
}
static ServerResponse.BodyBuilder temporaryRedirect(URI location) {
ServerResponse.BodyBuilder builder = status(HttpStatus.TEMPORARY_REDIRECT);
return (ServerResponse.BodyBuilder)builder.location(location);
}
static ServerResponse.BodyBuilder permanentRedirect(URI location) {
ServerResponse.BodyBuilder builder = status(HttpStatus.PERMANENT_REDIRECT);
return (ServerResponse.BodyBuilder)builder.location(location);
}
static ServerResponse.BodyBuilder badRequest() {
return status(HttpStatus.BAD_REQUEST);
}
static ServerResponse.HeadersBuilder<?> notFound() {
return status(HttpStatus.NOT_FOUND);
}
static ServerResponse.BodyBuilder unprocessableEntity() {
return status(HttpStatus.UNPROCESSABLE_ENTITY);
}
public interface Context {
List> messageWriters();
List viewResolvers();
}
public interface BodyBuilder extends ServerResponse.HeadersBuilder {
ServerResponse.BodyBuilder contentLength(long var1);
ServerResponse.BodyBuilder contentType(MediaType var1);
ServerResponse.BodyBuilder hint(String var1, Object var2);
> Mono body(P var1, Class var2);
> Mono body(P var1, ParameterizedTypeReference var2);
Mono syncBody(Object var1);
Mono body(BodyInserter<?, ? super ServerHttpResponse> var1);
Mono render(String var1, Object... var2);
Mono render(String var1, Map var2);
}
public interface HeadersBuilder {
B header(String var1, String... var2);
B headers(Consumer var1);
B cookie(ResponseCookie var1);
B cookies(Consumer> var1);
B allow(HttpMethod... var1);
B allow(Set var1);
B eTag(String var1);
B lastModified(ZonedDateTime var1);
B location(URI var1);
B cacheControl(CacheControl var1);
B varyBy(String... var1);
Mono build();
Mono build(Publisher var1);
Mono build(BiFunction> var1);
}
}
回顾上述官方文档图片,还需配置路由以替代@RequestMapping的功能。利用RouterFunctions.route(RequestPredicate, HandlerFunction)提供的默认路由器函数实现,新建HiRouter类,代码如下:
package com.dalaoyang.router;
import com.dalaoyang.handler.HiHandler;
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;
/**
* @author dalaoyang
* @project springboot_learn
* @package com.dalaoyang.router
* @email yangyang@dalaoyang.cn
* @date 2026/7/30
*/
@Configuration
public class HiRouter {
@Bean
public RouterFunction routeCity(HiHandler hiHandler) {
return RouterFunctions
.route(RequestPredicates.GET("/hi")
.and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
hiHandler::Hi);
}
}
启动项目后,控制台打印出两种方式的映射信息,如图所示:

在浏览器中访问http://localhost:8080/hi,页面显示结果如图所示:

源码下载链接:大老杨码云
以上就是本文的全部内容,希望对各位的学习有所帮助,也欢迎大家多多支持本站。