美文网首页
Spring Boot中使用@Async实现异步调用

Spring Boot中使用@Async实现异步调用

作者: 夜空最亮的9星 | 来源:发表于2018-08-28 05:19 被阅读17次

    Spring Boot中使用@Async实现异步调用

    使用@Async实现异步调用

    启动加上@EnableAsync ,需要执行异步方法上加入 @Async

    在方法上加上@Async之后 底层使用多线程技术

    @Component
    public class Task {
    
     public static Random random =new Random();
    
         @Async
        public void doTaskOne() throws Exception {
            System.out.println("开始做任务一");
            long start = System.currentTimeMillis();
            Thread.sleep(random.nextInt(10000));
            long end = System.currentTimeMillis();
            System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
        }
    
         @Async
        public void doTaskTwo() throws Exception {
            System.out.println("开始做任务二");
            long start = System.currentTimeMillis();
            Thread.sleep(random.nextInt(10000));
            long end = System.currentTimeMillis();
            System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
        }
         @Async
        public void doTaskThree() throws Exception {
            System.out.println("开始做任务三");
            long start = System.currentTimeMillis();
            Thread.sleep(random.nextInt(10000));
            long end = System.currentTimeMillis();
            System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
        }
    
    }
    
    

    为了让@Async注解能够生效,还需要在Spring Boot的主程序中配置@EnableAsync,如下所示:

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

    相关文章

      网友评论

          本文标题:Spring Boot中使用@Async实现异步调用

          本文链接:https://www.haomeiwen.com/subject/mnwxwftx.html