码迷,mamicode.com
首页 > 编程语言 > 详细

Springboot-async

时间:2019-06-04 17:41:03      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:new   display   for   类型   sep   ring   pack   isp   inter   

使用@Async实现异步调用

什么是”异步调用”与”同步调用”

“同步调用”就是程序按照一定的顺序依次执行,,每一行程序代码必须等上一行代码执行完毕才能执行;”异步调用”则是只要上一行代码执行,无需等待结果的返回就开始执行本身任务。 

通常情况下,”同步调用”执行程序所花费的时间比较多,执行效率比较差。所以,在代码本身不存在依赖关系的话,我们可以考虑通过”异步调用”的方式来并发执行。

 

“异步调用”

在 spring boot 框架中,只要提过@Async注解就能奖普通的同步任务改为异步调用任务。 

注意: @Async所修饰的函数不要定义为static类型,这样异步调用不会生效

 

1. 开启@Async注解

在Spring Boot主类添加@EnableAsync注解

 

2. 定义异步任务

定义Task类,创建三个处理函数分别模拟三个执行任务的操作,操作消耗时间随机取(10秒内)。

 

@Component

public class Task {

 

    //定义一个随机对象.

    public static Random random =new Random();

 

    @Async  //加入"异步调用"注解

    public void doTaskOne() throws InterruptedException {

        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 InterruptedException {

        System.out.println("开始执行任务二");

        long start = System.currentTimeMillis();

        Thread.sleep(random.nextInt(10000));

        long end = System.currentTimeMillis();

        System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");

    }

 

    @Async

    public void doTaaskThree() throws InterruptedException {

        System.out.println("开始执行任务三");

        long start = System.currentTimeMillis();

        Thread.sleep(random.nextInt(10000));

        long end = System.currentTimeMillis();

        System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");

    }

}

3. 创建Controller进行测试

注意@Autowired注入类,因为这个类已经被 Spring 管理了。如果使用 new 来获得线程类将不会执行异步效果,这里涉及到在 Spring 中使用多线程。

 

@Controller

public class TaskController {

 

    @Autowired

    private Task TASK;

 

    @ResponseBody

    @RequestMapping("/task")

    public String task() throws Exception {

        System.out.println("开始执行Controller任务");

        long start = System.currentTimeMillis();

        TASK.doTaskOne();

        TASK.doTaskTwo();

        TASK.doTaaskThree();

        long end = System.currentTimeMillis();

        System.out.println("完成Controller任务,耗时:" + (end - start) + "毫秒");

        return "success";

    }

}

4. 多次调用

访问 http://localhost:8080/task 截图: 
技术图片

使用@Async实现异步调用

什么是”异步调用”与”同步调用”

“同步调用”就是程序按照一定的顺序依次执行,每一行程序代码必须等上一行代码执行完毕才能执行;”异步调用”则是只要上一行代码执行,无需等待结果的返回就开始执行本身任务。 
通常情况下,”同步调用”执行程序所花费的时间比较多,执行效率比较差。所以,在代码本身不存在依赖关系的话,我们可以考虑通过”异步调用”的方式来并发执行。

“异步调用”

在 spring boot 框架中,只要提过@Async注解就能奖普通的同步任务改为异步调用任务。 
注意: @Async所修饰的函数不要定义为static类型,这样异步调用不会生效

1. 开启@Async注解

在Spring Boot主类添加@EnableAsync注解,如下:

@SpringBootApplication
@EnableAsync // 启用异步注解
@ComponentScan(basePackages="com.ideabook")
public class SpringbootStartApplication extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootStartApplication.class, args);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2. 定义异步任务

定义Task类,创建三个处理函数分别模拟三个执行任务的操作,操作消耗时间随机取(10秒内)。

@Service
public class AsyncService {
    public static Random random =new Random();

    @Async
    public Future<String> doTaskOne() throws Exception {
        System.out.println("开始做任务一");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
        return new AsyncResult<>("任务一完成");
    }

    @Async
    public Future<String> doTaskTwo() throws Exception {
        System.out.println("开始做任务二");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
        return new AsyncResult<>("任务二完成");
    }

    @Async
    public Future<String> doTaskThree() throws Exception {
        System.out.println("开始做任务三");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
        return new AsyncResult<>("任务三完成");
    }

    @Async
    public void  doTaskFour(){
        System.out.println("开始做任务四");
        long start = System.currentTimeMillis();
        long count = 0;
        for (int i = 0 ; i < 10000000; i ++){
           count = count + i ;
        }
        long end = System.currentTimeMillis();
        System.out.println("完成任务四,耗时:" + (end - start) + "毫秒");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

3. 创建Controller进行测试

注意@Autowired注入类,因为这个类已经被 Spring 管理了。如果使用 new 来获得线程类将不会执行异步效果,这里涉及到在 Spring 中使用多线程。

@Controller
@RequestMapping("/async")
public class AsyncController {

    private AsyncService asyncService;

    @Autowired
    public AsyncController(AsyncService asyncService) {
        this.asyncService = asyncService;
    }

    @RequestMapping("/test")
    @ResponseBody
    public String testAsync() throws Exception{
        long start = System.currentTimeMillis();

        Future<String> task1 = asyncService.doTaskOne();
        Future<String> task2 = asyncService.doTaskTwo();
        Future<String> task3 = asyncService.doTaskThree();
        asyncService.doTaskFour();
        while(true) { //等待功能全部完成后,再返回效果。类似于接口内部各个功能的异步执行,最后统一返回状态值。
            if(task1.isDone() && task2.isDone() && task3.isDone()) {
                // 三个任务都调用完成,退出循环
                break;
            }
           // Thread.sleep(1000);
        }

        long end = System.currentTimeMillis();

        System.out.println("任务全部完成,总耗时:" + (end - start) + "毫秒");
        return "Success!!";

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

备注:利用service中Future做为返回参数,可以对异步的操作进行管理。

Springboot-async

标签:new   display   for   类型   sep   ring   pack   isp   inter   

原文地址:https://www.cnblogs.com/lsfgg/p/10974796.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!