普通的Controller

 @GetMapping("/1")
    public String fun1() {
        log.info("get str in fun1 start");
        String str = createStr();
        log.info("get str in fun1 end");
        return str;
    }

后台log日志:
Web-Flux非阻塞编程
可以看出,请求fun1()这个controller用了单个线程去跑并且返回,任务耗时10秒,则方法调用开始到结束用时10秒

Mono


 @GetMapping("/2")
    public Mono<String> fun2() {
        log.info("get str in fun2 start");
        Mono<String> stringMono = Mono.fromSupplier(this::createStr);
        log.info("get str in fun2 end");
        return stringMono;
    }

Web-Flux非阻塞编程
应为采用了异步FLUX编程模型,在这个方法内,主线程会为工作方法开一个线程去跑,而主线程立即返回,不发生阻塞,直到工作线程调用结束之后,将结果返回给前端

Flux

 @GetMapping(value = "/3",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> fun3() throws InterruptedException {
        log.info("get str in fun2 start");
        Flux<String> result = Flux.fromStream(IntStream.range(1, 5).mapToObj(x -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return String.valueOf(x);
        }));
        log.info("get str in fun2 end");
        return result;

    }

执行结果:
Web-Flux非阻塞编程

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-17
  • 2022-02-07
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-20
  • 2021-09-21
  • 2021-08-31
  • 2021-07-02
  • 2021-11-11
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案