@RestController
@Slf4j
public class UserController {
@RequestMapping("/index")
public String index(){
log.info("springmvc index begin");
String result="cc666";
log.info("springmvc index end");
return result;
@RequestMapping("/index2")
public Mono<String> index2(){
log.info("webflux index begin");
Mono<String> result=Mono.just("666cc");
log.info("webflux index end");
return result;
springmvc
2020-08-04 21:28:57.430 INFO 14156 --- [ctor-http-nio-2] c.w.webflux.controller.UserController : springmvc index begin
2020-08-04 21:29:00.430 INFO 14156 --- [ctor-http-nio-2] c.w.webflux.controller.UserController : springmvc index end
webflux
2020-08-04 21:29:09.640 INFO 14156 --- [ctor-http-nio-2] c.w.webflux.controller.UserController : webflux index begin
2020-08-04 21:29:09.641 INFO 14156 --- [ctor-http-nio-2] c.w.webflux.controller.UserController : webflux index end
4.添加数据库支持
对于数据库的支持,webflux用到的是r2dbc这样一个东西。
R2DBC(Reactive Relational Database Connectivity)是一个使用反应式驱动集成关系数据库的孵化器。Spring Data R2DBC运用熟悉的Spring抽象和repository 支持R2DBC。基于此,在响应式程序栈上使用关系数据访问技术,构建由Spring驱动的程序将变得非常简单。
@Table("user")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String username;
private String password;
@PostMapping("/save")
public Mono save(@RequestBody User user){
return this.userDao.save(user);
@DeleteMapping("/delete/{id}")
public Mono delete(@PathVariable Long id){
return this.userDao.deleteById(id);
@GetMapping("/get/{id}")
public Mono get(@PathVariable Long id){
return this.userDao.findById(id);
@Component
@AllArgsConstructor
public class UserHandler {
private final UserDao userDao;
public Mono<ServerResponse> saveUser(ServerRequest request){
Mono<User> mono=request.bodyToMono(User.class);
User user = mono.block();
return ServerResponse.ok().build(this.userDao.save(user).then());
public Mono<ServerResponse> deleteById(ServerRequest request){
Long id=Long.parseLong(request.pathVariable("id"));
return ServerResponse.ok().build(this.userDao.deleteById(id).then());
public Mono<ServerResponse> getByid(ServerRequest request){
Long id=Long.parseLong(request.pathVariable("id"));
Mono<User> mono = this.userDao.findById(id);
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(mono,User.class);
public Mono<ServerResponse> findAll(ServerRequest request){
Flux<User> all = this.userDao.findAll();
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(all,User.class);