spring boot实现异步调用

今天在这里学习下使用springboot的异步调用async

首先使用@EnableAsync开启异步功能

/**
* @author fengzp
 * @date 17/5/8
 * @email fengzp@gzyitop.com
 * @company 广州易站通计算机科技有限公司
 */
@SpringBootApplication
@EnableAsync
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

测试类

    /**
 * @author fengzp
 * @date 17/5/8
 * @email fengzp@gzyitop.com
 * @company 广州易站通计算机科技有限公司
 */
@Component
public class AsyncTest {

    public static Random random =new Random();

    /**
     * @Async所修饰的函数不要定义为static类型,否则异步调用不会生效
     *
     * 这里通过返回Future<T>来返回异步调用的结果,实现异步回调
     */
    @Async
    public Future<String> test1() throws InterruptedException {
        System.out.println("test1 begin");
        long begin = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        System.out.println("test1 end " + (System.currentTimeMillis() - begin));
        return new AsyncResult<String>("test1 is done!");
    }

    @Async
    public Future<String> test2() throws InterruptedException {
        System.out.println("test2 begin");
        long begin = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        System.out.println("test2 end " + (System.currentTimeMillis() - begin));
        return new AsyncResult<String>("test2 is done!");
    }

    @Async
    public Future<String> test3() throws InterruptedException {
        System.out.println("test3 begin");
        long begin = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        System.out.println("test3 end " + (System.currentTimeMillis() - begin));
        return new AsyncResult<String>("test3 is done!");
    }
}

测试

/**
 * @author fengzp
 * @date 17/5/8
 * @email fengzp@gzyitop.com
 * @company 广州易站通计算机科技有限公司
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class Test {

    @Autowired
    AsyncTest asyncTest;

    @org.junit.Test
    public void test() throws InterruptedException {
        System.out.println("begin");
        long begin = System.currentTimeMillis();
        Future<String> test1 = asyncTest.test1();
        Future<String> test2 = asyncTest.test2();
        Future<String> test3 = asyncTest.test3();

        while(true) {
            if(test1.isDone() && test2.isDone() && test3.isDone())
                break;

            Thread.sleep(500);
        }

        System.out.println("end 耗时: " + (System.currentTimeMillis() - begin));
    }
}

运行结果

954438-20170508113029691-16708084.png

转载于:https://www.cnblogs.com/andyfengzp/p/6824253.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值