這章節將會運用Spring WebFlux來實作REST API的功能。
引入以下dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
SpringMVC的endpoint method:
@RestController
@RequestMapping(path="/api/orders", produces="application/json")
@CrossOrigin(origins="*")
public class OrderController {
...
@GetMapping(params="recent")
public Iterable<Order> recentOrders() {
PageRequest page = PageRequest.of(0, 12, Sort.by("createdAt").descending());
return orderRepo.findAll(page).getContent();
}
...
}
運用WebFlux,將回傳的Iterable改為Flux:
@GetMapping(params="recent")
public Flux<Order> recentOrders() {
return Flux.fromIterable(orderRepo.findAll()).take(12);
}
不過可以發現,在orderRepo還是運用了原來的方法,也可以直接在repository中改成reactive programming,就會變成:
@GetMapping(params="recent")
public Flux<Order> recentOrders() {
return orderRepo.findAll().take(12);
}
現在來改寫一下orderById:
@GetMapping("/{id}")
public Order orderById(@PathVariable("id") Long id) {
Optional<Order> optOrder = orderRepo.findById(id);
if (optOrder.isPresent()) {
return optOrder.get();
}
return null;
}
可以改為:
@GetMapping("/{id}")
public Mono<Order> orderById(@PathVariable("id") Long id) {
return orderRepo.findById(id);
}
Spring MVC的postOrder:
@PostMapping(consumes="application/json")
@ResponseStatus(HttpStatus.CREATED)
public Order postOrder(@RequestBody Order order) {
return orderRepo.save(order);
}
改成reactive:
@PostMapping(consumes = "application/json")
@ResponseStatus(HttpStatus.CREATED)
public Mono<Order> postOrder(@RequestBody Mono<Order> orderMono) {
return orderRepo.saveAll(orderMono).next();
}
也可如下寫:
@PostMapping(consumes = "application/json")
@ResponseStatus(HttpStatus.CREATED)
public Mono<Order> postOrder(@RequestBody Mono<Order> orderMono) {
return orderMono.flatMap(orderRepo::save);
}