Spring Boot 中@Aynsc的用法详解

Spring Boot 中@Aynsc的用法

1. 启用Aynsc

1.1 添加pom依赖

 
     org.springframework.boot
     spring-boot-starter-web

1.2 在启动类添加@EnableAsync注解

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

1.3 在service中使用@Async注解

这里我们用一个用户注册并发送邮件的场景来说明

controller

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MailService mailService;

    @GetMapping("/register")
    public String register(){
        try {
            long start = System.currentTimeMillis();
            userService.insert();
            mailService.sendMail();
            log.info("执行时间"+(System.currentTimeMillis()-start));
            return "注册成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "注册失败";
    }
}

UserService

@Service
@Slf4j
public class UserService {

    public void insert(){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("添加用户成功");
    }
}

MailService

@Service
@Slf4j
public class MailService {
    
    @Async
    public void sendMail(){
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("发送邮件成功");
    }
}

正常如果不使用异步调用的方式时,我们的注册流程耗时应该是11000+ms

使用异步以后耗时情况

2018-11-23 09:44:27.462  INFO 2600 --- [nio-8080-exec-1] com.example.async.service.UserService    : 添加用户成功
2018-11-23 09:44:27.470  INFO 2600 --- [nio-8080-exec-1] c.e.async.controller.UserController      : 执行时间1009
2018-11-23 09:44:37.478  INFO 2600 --- [         task-1] com.example.async.service.MailService    : 发送邮件成功

可以看到耗时只有1009ms

2. 带有返回值的异步

这时候注册流程发生了变化,注册的同时要通过外部系统获取用户的信息更新到本地数据库

修改controller

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MailService mailService;

    @Autowired
    private OuterService outerService;

    @GetMapping("/register")
    public String register(){
        try {
            long start = System.currentTimeMillis();
            Future userInfoFuture = outerService.getUserInfo();
            userService.insert();
            mailService.sendMail();
            String userInfo = userInfoFuture.get();
            userService.update(userInfo);
            log.info("执行时间"+(System.currentTimeMillis()-start));
            return "注册成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "注册失败";
    }
}

OuterService

@Service
@Slf4j
public class OuterService {

    @Async
    public Future getUserInfo(){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error("获取用户详情失败",e);
        }
        log.info("获取用户详情成功");
        return new AsyncResult<>("success");
    }
}

执行日志

2018-11-23 10:04:01.353  INFO 9240 --- [nio-8080-exec-2] com.example.async.service.UserService    : 添加用户成功
2018-11-23 10:04:01.356  INFO 9240 --- [         task-1] com.example.async.service.OuterService   : 获取用户详情成功
2018-11-23 10:04:01.358  INFO 9240 --- [nio-8080-exec-2] com.example.async.service.UserService    : 更新用户成功
2018-11-23 10:04:01.358  INFO 9240 --- [nio-8080-exec-2] c.e.async.controller.UserController      : 执行时间1010
2018-11-23 10:04:11.362  INFO 9240 --- [         task-2] com.example.async.service.MailService    : 发送邮件成功

3. 异常处理

3.1 带有返回值的异常处理

当一个@Async方法有一个Future类型的返回值时,在调Future的get()方法获取任务的执行结果时抛出的异常。

修改OuterService

@Service
@Slf4j
public class OuterService {

    @Async
    public Future getUserInfo() throws Exception {
        try {
            Thread.sleep(1000);
            throw new Exception("获取用户详情异常");
        } catch (InterruptedException e) {
            log.error("获取用户详情失败",e);
        }
        log.info("获取用户详情成功");
        return new AsyncResult<>("success");
    }
}

执行结果

2018-11-23 10:49:26.085  INFO 3752 --- [nio-8080-exec-1] com.example.async.service.UserService    : 添加用户成功
2018-11-23 10:49:26.106 ERROR 3752 --- [nio-8080-exec-1] c.e.async.controller.UserController      : java.lang.Exception: 获取用户详情异常
2018-11-23 10:49:36.090  INFO 3752 --- [         task-2] com.example.async.service.MailService    : 发送邮件成功

我们看到添加和发送邮件成功了 在String userInfo = userInfoFuture.get();处抛出了异常

3.2 不带返回值的异常处理

不带返回值的异常无法被调用者捕获,我们可以实现AsyncUncaughtExceptionHandler来处理异常

创建MyAsyncUncaughtExceptionHandler实现AsyncUncaughtExceptionHandler

@Slf4j
public class MyAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {

    @Override
    public void handleUncaughtException(Throwable ex, Method method, Object... params) {
        log.error("ex=",ex);
        // doSomething....
    }
}

创建AsyncConfig实现AsyncConfigurer并覆盖AsyncUncaughtExceptionHandler方法

@Configuration
@Slf4j
public class AsyncConfig implements AsyncConfigurer {
   
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new MyAsyncUncaughtExceptionHandler();
    }
}

4. 自定义线程池

Spring boot 默认配置的线程池是ThreadPoolTaskExecutor,我们可以通过一些配置来配置线程池

spring.task.execution.pool.core-size=8
spring.task.execution.pool.max-threads=16
spring.task.execution.pool.queue-capacity=100
spring.task.execution.pool.keep-alive=10s

这会将线程池更改为使用有界队列,最小线程数为8,最大线程数为16,队列最大数量为100,当线程空闲10秒(而不是默认情况下的60秒)时回收线程时

如果我们想更清楚的控制线程池,也可以配置我们自己的线程池

修改AsyncConfig

@Configuration
@Slf4j
public class AsyncConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("my-executor-");
        //如果不初始化,导致找到不到执行器
        executor.initialize();
        return executor;
    }
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new MyAsyncUncaughtExceptionHandler();
    }
}

这里我们自定义了我们线程池的前缀改成了my-executor-

2018-11-23 16:02:04.797  INFO 15588 --- [nio-8080-exec-2] com.example.async.service.UserService    : 添加用户成功
2018-11-23 16:02:04.800  INFO 15588 --- [  my-executor-1] com.example.async.service.OuterService   : 获取用户详情成功
2018-11-23 16:02:04.800  INFO 15588 --- [nio-8080-exec-2] com.example.async.service.UserService    : 更新用户成功
2018-11-23 16:02:04.800  INFO 15588 --- [nio-8080-exec-2] c.e.async.controller.UserController      : 执行时间1006
2018-11-23 16:02:14.799  INFO 15588 --- [  my-executor-2] com.example.async.service.MailService    : 发送邮件成功

5. 多个线程池

有时候我们想让我们的线程池只做一件事防止多个共用线程池出线抢占溢出情况

我们在AsyncConfig中添加两个线程池mailExecutor和outerExecutor

@Configuration
@Slf4j
public class AsyncConfig implements AsyncConfigurer {


    @Bean
    public Executor mailExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("mail-executor-");
        executor.initialize();
        return executor;
    }
    @Bean
    public Executor outerExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("out-executor-");
        executor.initialize();
        return executor;
    }
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(10);
        executor.setThreadNamePrefix("my-executor-");
        //如果不初始化,导致找到不到执行器
        executor.initialize();
        return executor;
    }
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new MyAsyncUncaughtExceptionHandler();
    }
}

然后我们service中分别使用这两个线程池

MailService使用mailExecutor

@Service
@Slf4j
public class MailService {

    @Async("mailExecutor")
    public void sendMail() throws Exception {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        }
        log.info("发送邮件成功");
    }
}

OuterService使用outerExecutor

@Service
@Slf4j
public class OuterService {

    @Async("outerExecutor")
    public Future getUserInfo() throws Exception {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error("获取用户详情失败",e);
        }
        log.info("获取用户详情成功");
        return new AsyncResult<>("success");
    }
}

运行效果

2018-11-23 16:18:01.696  INFO 1552 --- [ out-executor-2] com.example.async.service.OuterService   : 获取用户详情成功
2018-11-23 16:18:01.696  INFO 1552 --- [nio-8080-exec-5] com.example.async.service.UserService    : 添加用户成功
2018-11-23 16:18:01.697  INFO 1552 --- [nio-8080-exec-5] com.example.async.service.UserService    : 更新用户成功
2018-11-23 16:18:01.697  INFO 1552 --- [nio-8080-exec-5] c.e.async.controller.UserController      : 执行时间1001
2018-11-23 16:18:11.699  INFO 1552 --- [mail-executor-2] com.example.async.service.MailService    : 发送邮件成功

完!

你可能感兴趣的:(Spring Boot 中@Aynsc的用法详解)