Springboot 2响应式编程 WebFlux 初体验

Spring boot 应用可以添加依赖spring-boot-starter-webflux来构建响应式 Web 应用程序。

内置响应式服务器

Spring Boot WebFlux 内置 Reactor Netty、Tomcat、Jetty 和 Undertow。默认端口是 8080。

WebFlux 的 CRUD 示例

Springboot WebFlux 将路由配置与请求的实际处理流程分开,如下示例。

@Configuration
public class UserFluxController {

  @Bean
  public RouterFunction<ServerResponse> monoRouterFunction(UserFluxController userHandler) {
    return RouterFunctions
        .route(GET("/flux/list").and(accept(APPLICATION_JSON)), userHandler::findAll)
        .andRoute(GET("/flux/{id}").and(accept(APPLICATION_JSON)), userHandler::findOne)
        .andRoute(POST("/flux").and(accept(APPLICATION_JSON)), userHandler::save)
        .andRoute(PUT("/flux/{id}").and(accept(APPLICATION_JSON)), userHandler::update)
        .andRoute(DELETE("/flux/{id}").and(accept(APPLICATION_JSON)), userHandler::delete);
  }

  private UserService service;

  @Autowired
  public UserFluxController(UserService service) {
    this.service = service;
  }

  /**
   * 查找列表. 成功返回200.
   */
  Mono<ServerResponse> findAll(ServerRequest request) {
    Object currentPage = request.attribute("currentPage").orElse(1);
    Object pageSize = request.attribute("pageSize").orElse(10);
    Page page = new Page((Integer) currentPage, (Integer) pageSize);

    return ok().body(fromObject(service.findAll(page)));
  }

  /**
   * 查找详情. 成功返回200.
   */
  Mono<ServerResponse> findOne(ServerRequest request) {
    return ok().body(fromObject(service.findOne(request.pathVariable("id"))));
  }

  /**
   * 新建. 成功返回201.
   */
  Mono<ServerResponse> save(ServerRequest request) {
    return request.bodyToMono(UserVo.class).flatMap(user -> created(URI.create("")).body(fromObject(service.save(user))));
  }

  /**
   * 更新. 成功返回201.
   */
  Mono<ServerResponse> update(ServerRequest request) {
    String id = request.pathVariable("id");
    return request.bodyToMono(UserVo.class).flatMap(user -> {
      user.setId(id);
      return created(URI.create("")).body(fromObject(service.update(user)));
    });
  }

  /**
   * 删除. 成功返回204.
   */
  Mono<ServerResponse> delete(ServerRequest request) {
    service.delete(request.pathVariable("id"));
    return noContent().build();
  }
}
posted @ 2019-08-20 01:24  O&#39;Neal  阅读(845)  评论(0编辑  收藏  举报