Spring WebFlux学习笔记(一)

核心思想

WebFlux主要是异步

例子

参考一个源码:
https://blog.youkuaiyun.com/qq_43923045/article/details/106309432?spm=1001.2014.3001.5506

@GetMapping("/delay1")
    public Mono<RestResult> delayResult() {
        long l = System.currentTimeMillis();

        Mono<RestResult> resultMono = Mono.fromSupplier(()->{
            try {
                Thread.sleep(5_000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return new RestResult().setMessage("hello world!!");

        });
        long r = System.currentTimeMillis();
        log.info("执行时间 {} !!",(r-l));
        return resultMono;
    }


@GetMapping("/delay2")
    public  RestResult  delayResult2() {
        long l = System.currentTimeMillis();
        Supplier<RestResult> result = () -> {
            try {
                Thread.sleep(5_000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return new RestResult<>().setMessage("ok");
        };
        RestResult restResult = result.get();
        long r = System.currentTimeMillis();

        log.info("执行时间 {} !!",(r-l));
        return restResult;
    }

如上面的代码例子,delay1接口会直接打印执行时间。delay2会等待一段时间才能打印执行时间。

扩展

思考:
对于delay1接口,什么时候才有返回结果呢?
答案:
返回需要加上MediaType.APPLICATION_STREAM_JSON_VALUE

@GetMapping(value = "/stream",produces = MediaType.APPLICATION_STREAM_JSON_VALUE)

参考资料https://blog.youkuaiyun.com/weixin_34364071/article/details/91664821?spm=1001.2014.3001.5506

遗留问题

1、那使用postman等工具测试例子的2个接口的时间到底是多少?
2、前端怎么去处理异步返回的结果?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值