SpringBoot-函数式Web
流程
- 给容器中放一个Bean:类型为
RouterFunction<ServerResponse>
,集中所有路由信息
- 每个业务准备一个自己的Handler
四大核心对象
- RouterFunction:定义路由信息。发什么请求,谁来处理
- RequestPredicates:定义请求:请求谓语。请求方式、请求参数
- ServerRequest:封装请求完整数据
- ServerResponse:封装响应完整数据
示例代码
配置类
java
复制代码
@Configuration
public class WebFunctionConfig {
@Bean
public RouterFunction<ServerResponse> router(UserBizHandler userBizHandler) {
return RouterFunctions.route()
.GET("/user/{id}", RequestPredicates.accept(MediaType.ALL), userBizHandler::getUser)
.GET("/users", RequestPredicates.accept(MediaType.ALL), userBizHandler::getUsers)
.POST("/user", RequestPredicates.accept(MediaType.APPLICATION_JSON), userBizHandler::createUser)
.DELETE("/user/{id}", RequestPredicates.accept(MediaType.ALL), userBizHandler::deleteUser)
.build();
}
}
业务类
java
复制代码
package com.vmware.service;
import com.vmware.domain.User;
import jakarta.servlet.ServletException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.function.ServerRequest;
import org.springframework.web.servlet.function.ServerResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class UserBizHandler {
public ServerResponse getUser(ServerRequest request) {
User user = new User("张三", "12345678");
return ServerResponse.ok().body(user);
}
public ServerResponse getUsers(ServerRequest request) {
List<User> users = new ArrayList<>();
users.add(new User("张三","1234"));
users.add(new User("李四","abc"));
users.add(new User("王五","hello"));
//body中的对象就是@ResponseBody的原理,利用HttpMessageConverter写出为json
return ServerResponse.ok().body(users);
}
public ServerResponse createUser(ServerRequest request) throws ServletException, IOException {
User user = request.body(User.class);
log.info("创建用户:{}",user);
return ServerResponse.ok().build();
}
public ServerResponse deleteUser(ServerRequest request){
String id = request.pathVariable("id");
log.info("删除用户:{}",id);
return ServerResponse.ok().build();
}
}