美文网首页
A.10 springboot async

A.10 springboot async

作者: 成长的键盘手 | 来源:发表于2018-02-12 23:41 被阅读0次

1. 背景

服务端为了达到快速响应接口调用方的,通常使用的办法是将业务中部分非事物及非关键步骤改为异步执行,从而提高接口的响应速度。使用异步的方法有消息队列,内存队列,开启线程等,本文主要讲解在springboot环境中如何使用线程进行异步。

在非Spring项目或者普通的java项目中,想要实现异步大多是使用多线程,可以自己实现Runnable接口或者继承Thread类,或者使用Executors线程池。

2. spring环境下的异步

Spring(SpringBoot)中则提供了方便的方法执行异步调用。
异步常见的两种情况:

  • 无返回值的异步
  • 有返回值的异步

2.1 开启异步调用

增加 @EnableAsync 注解

@SpringBootApplication
@EnableAsync
public class DemoApp {

    private static ConfigurableApplicationContext ctx;
    
    public static void main(String[] args) {
        ctx = SpringApplication.run(DemoApp.class, args);
    }
}

2.2 无返回值的异步

1、异步方法

在方法体上增加有 @Async 的方法即为异步方法

@Service
public class TaskService {
    
    @Async
    public void task1(String name) {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Hello, " + name);
    }
    
    @Async
    public void task2(String name) {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Bye, " + name);
    }
}

2、调用方法

通过测试能够发现,task1方法和task2方法在没有执行完成的情况下,主线程已经将结果返回。明显起到了异步的效果。有效的减少了主线程的响应时间。

@RestController
@Api(tags="异步测试")
@RequestMapping(path="task")
public class TaskController {
    
    @Autowired
    private TaskService taskService;
    
    @RequestMapping(path="one", method=RequestMethod.GET)
    public ResponseEntity<String> one() {
        //子线程异步执行
        taskService.task1("Tom");
        taskService.task2("Tom");
        //主线程返回提前返回数据
        return ResponseEntity.ok().body("success");
    }
}

2.3 有返回值的异步

1、异步方法

在方法体上增加有 @Async 的方法即为异步方法

@Service
public class TaskFutureService {
    
    @Async
    public Future<String> task1(String name) {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new AsyncResult<String>("Hello, " + name);
    }
    
    @Async
    public Future<String> task2(String name) {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new AsyncResult<String>("Bye, " + name);
    }
}

2、异步调用

通过测试能够发现,task1方法和task2方法会并发执行,主线程会一直等待 task1 和 task2 的方法执行完成过后拿到具体的返回值,有效的减少的程序的总运行时间。

@RestController
@Api(tags="异步测试")
@RequestMapping(path="task")
public class TaskController {
    
//  @Autowired
//  private TaskService taskService;
    
    @Autowired
    private TaskFutureService taskFutureService;
 
//  @RequestMapping(path="one", method=RequestMethod.GET)
//  public ResponseEntity<String> one() {
//      //子线程异步执行
//      taskService.task1("Tom");
//      taskService.task2("Tom");
//      //主线程返回提前返回数据
//      return ResponseEntity.ok().body("success");
//  }

    @RequestMapping(path = "tow", method = RequestMethod.GET)
    public ResponseEntity<String> tow() {
        //子线程异步执行
        Future<String> task1 = taskFutureService.task1("Tom");
        Future<String> task2 = taskFutureService.task2("Tom");
        //主线程等待返回结果
        while (true) {
            if (task1.isDone() && task2.isDone()) {
                // 三个任务都调用完成,退出循环等待
                break;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        String result = null;
        try {
            result = task1.get() + "..." + task2.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok().body(result);
    }
}

2.4 线程池配置

当主线程的线程达到一定程度时候,主线程异步开启的子线程会几何数上涨,为了减少线程打开关闭的开销,所以使用线程池是必须的。

1、线程池的配置

@Bean
public AsyncTaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(8);//核心线程数
    executor.setMaxPoolSize(32);// 最大线程数
    executor.setQueueCapacity(64);//队列最大长度
    executor.setThreadNamePrefix("task-executor");
    
    // rejection-policy:饱和策略,当pool已经达到max size的时候,如何处理新任务
    // 1.CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
    // 2.ABORT_RUNS:默认策略,抛出RejectedExecutionException异常 终止
    // 3.DISCARD_OLDEST_RUNS:当新提交的任务无法保存到队列中等待执行时将抛弃最旧的任务,然后尝试提交新任务
    // 4.DiscardPolicy:不能执行的任务将被丢弃
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    executor.initialize();
    return executor;
}

2、使用线程池。(需要在@Async注解上增加线程池名称)

@Async("taskExecutor")
public void task1(String name) {
    try {
        TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("Hello, " + name);
}

相关文章

网友评论

      本文标题:A.10 springboot async

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