使用反应式spring-webflux

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hxg117/article/details/79697958

本文使用spring-boot 2.0。 Maven依赖需要导入:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

下面新建一个简单的Controller,一个使用GET,一个使用POST。该Controller使用到了一个简单的值对象User,它里面仅有两个属性id 和name。这里省略。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
public class HomeController {

    @GetMapping("/users")
    public Flux<User> images() {
        return Flux.just(
                new User(1, "AAA"),
                new User(2, "BBB"),
                new User(3, "CCC"));
    }

    @PostMapping("/users")
    public Mono<Void> create(@RequestBody Flux<User> users) {
        return users.map(user -> {
            System.out.println("Save user " + user.getName());
            return user;
        }).then();
    }
}

这里面有两个新的概念

  • Flux:类似于Java8里面的Stream,但是Flux是Reactive的,非阻塞异步。
  • Mono: 也类似于Java8里面的Stream,和Flux的区别是,Mono只包含一个对象。

Flux和Mono主要思想是反应式编程。在上面的例子中返回了一个Flux,而不是List< User>, 表示数据只有在subscribe的时候才会准备好。

请看下面的例子,当返回一个Mono< String>时,callable并没有执行。只有在使用subscribe的时候,才会真正的执行callable。

public static void main(String[] args) {
    Mono<String> mono = Mono.fromCallable(() -> {
        System.out.println("This is called");
        return "ABC";
    });

    System.out.println("The callable is not prepared");
    mono.subscribe(System.out::println);
}

猜你喜欢

转载自blog.csdn.net/hxg117/article/details/79697958