springboot中任务异步执行

并行与并发场景下,异步执行是不可少的。这里来看一下在springboot中如何使用注解的方式执行异步任务?

首先创建一个springboot项目,在主函数类上加入@EnableAsync注解开启异步功能,如下所示:

@SpringBootApplication
@EnableAsync
public class SpringbootAcTaskApplication {

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

}

然后创建一个类,用@Async注解标明一个异步方法即可,如下所示:

@Component
class AsyncRun {
    @Async
    void async() {
        System.out.println("async running");
    }

    @Async
    Future<String> asyncFuture() {
        System.out.println("async-future running");
        return new AsyncResult<>("async-future run");
    }
}

下面是一个用来调用异步方法的测试类:

@Component
public class AsyncDemo implements CommandLineRunner {

    @Resource
    private AsyncRun asyncRun;

    @Override
    public void run(String... args) throws Exception {
        System.out.println("begin");
        asyncRun.async();
        Future<String> future = asyncRun.asyncFuture();
        System.out.println("end");
        System.out.println(future.get(1, TimeUnit.SECONDS));
    }
}

你可能感兴趣的:(springboot实战)