springboot有返回值异步任务调用

springboot有返回值异步任务调用

  1. 编写异步调用方法
    在实际开发中常常会遇到需要返回值的异步调用,示例代码如下:
@Async
    public Future<Integer> dealA() throws Exception{
        System.out.println("开始分析并处理业务A数据");
        long startTime = System.currentTimeMillis();
        Thread.sleep(4000);
        //模拟定义一个结果
        int count = 123456;
        long endTime = System.currentTimeMillis();
        System.out.println("业务A耗时"+(endTime-startTime));
        return new AsyncResult<Integer>(count);
    }
    
    @Async
    public Future<Integer> dealB() throws Exception{
        System.out.println("开始分析并处理业务B数据");
        long startTime = System.currentTimeMillis();
        Thread.sleep(5000);
        //模拟定义一个结果
        int count = 654321;
        long endTime = System.currentTimeMillis();
        System.out.println("业务B耗时"+(endTime-startTime));
        return new AsyncResult<Integer>(count);
    }
  1. 项目启动在浏览器访问:localhost:8080/staticsstatics, 测试异步任务请求,会发现浏览器相应"success"信息需要一段时间,此时查看控制台输出效果.从结果来看执行staticsstatics()方法并调用异步方法处理.要强调的是,异步方法有返回值的,当返回值较多时主流程在执行异步方法是会有短暂阻塞的,需要等待并获取异步方法的返回结果,而调用的2个异步方法会作为2个子线程并行执行,直到异步方法执行完成并返回结果,这样主流程会在最后一个异步方法返回结果后跳出阻塞状态.
    在这里插入图片描述
发布了4 篇原创文章 · 获赞 1 · 访问量 204

猜你喜欢

转载自blog.csdn.net/weixin_40914261/article/details/103438670