Spring 5 WebFlux入门教程

WebFlux是Spring 5 新增特性,提供响应式web应用。本文我们利用RestController 和 WebClient组件实现简单的响应式Restful应用。

Spring WebFlux Framework

WebFlux内部使用Project Rector并实现了——Flux 和 Mono 。新的框架支持两种编程模型:

  • 基于注解方式响应式组件
  • 函数式路由和处理

本文聚焦基于注解响应式组件。

我们需要增加 spring-boot-starter-webflux 依赖,它自动拉取其他依赖:

  • spring-bootspring-boot-starter
  • spring-webflux
  • reactor-corereactor-netty
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>

Reactive REST 应用示例

下面我们构建简单Reactive REST员工管理应用,使用 Spring WebFlux:

  • 使用简单领域对象——Employee ,包括id 和name
  • 使用RestController 构建Rest api ,发布 Employee资源,单个资源和列表资源
  • 使用WebClient作为客户端获取资源
  • WebFlux 和 Spring Security 保护响应式请求

响应式RestController

WebFlux 支持注解方式配置,与Spring Web mvc框架一样。我们在服务端创建注解Controller发布响应式Employee资源流。

@RestController
@RequestMapping("/employees")
public class EmployeeController {

    private final EmployeeRepository employeeRepository;
    
    // constructor...
}

EmployeeRepository 可以是任意支持非阻塞响应式流的数据访问层。对于不支持非阻塞的数据访问数据库,可以使用线程池进行转换。

单个资源

下面定义返回单个资源的请求:

@GetMapping("/{id}")
private Mono<Employee> getEmployeeById(@PathVariable String id) {
    return employeeRepository.findEmployeeById(id);
}

这里使用*Mono* 包装,因为最多就返回一个对象。

集合资源

下面定义请求返回所有Employee对象集合:

@GetMapping
private Flux<Employee> getAllEmployees() {
    return employeeRepository.findAllEmployees();
}

对于集合资源,使用Flux,返回0 或 n个元素。

响应式 WebClient

WebClient 是Spring 5 引入支持响应式流的非阻塞客户端。我们可以使用WebClient创建客户端,从EmployeeController请求获取数据:

public class EmployeeWebClient {

    WebClient client = WebClient.create("http://localhost:8080");

    // ...
}

上面使用create方法创建WebClient ,它执行 localhost:8080 ,因此我们可以使用相对路径调用请求。

返回单个资源

/employees/{id} 请求路径获取Mono类型的单个资源:

Mono<Employee> employeeMono = client.get()
  .uri("/employees/{id}", "1")
  .retrieve()
  .bodyToMono(Employee.class);

employeeMono.subscribe(System.out::println);

返回集合资源

类似 /employees路径返回集合资源:

Flux<Employee> employeeFlux = client.get()
  .uri("/employees")
  .retrieve()
  .bodyToFlux(Employee.class);
        
employeeFlux.subscribe(System.out::println);

WebFlux 安全管理

可以使用Spring Security 保护响应式请求。我们继续再EmployeeController中增加更新请求,让用户可以对已存在的员工进行更新操作,但该操作仅由管理员角色可以使用。首先增加新的方法:

@PostMapping("/update")
private Mono<Employee> updateEmployee(@RequestBody Employee employee) {
    return employeeRepository.updateEmployee(employee);
}

创建SecurityConfig ,定义基于路径的访问规则,仅容许ADMIN角色执行更新请求:

@EnableWebFluxSecurity
public class EmployeeWebSecurityConfig {

    // ...

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(
      ServerHttpSecurity http) {
        http.csrf().disable()
          .authorizeExchange()
          .pathMatchers(HttpMethod.POST, "/employees/update").hasRole("ADMIN")
          .pathMatchers("/**").permitAll()
          .and()
          .httpBasic();
        return http.build();
    }
}

上面示例只有管理员用户可以执行操作,最后使用 @EnableWebFluxSecurity 注解增加 Spring Security WebFlux的缺省配置。

总结

本文通过示例展示如何创建Spring WebFlux 框架支持的响应式web应用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值