【Springboot】之 异步处理(@Async)

前言

使用异步是为了缩短等待时间。
即:主线程尽早处理完并返回信息,能更快响应;而副线程执行其他操作用于完善。

一、配置类


作用:配置线程池,实现线程复用。

  1. 通过 @EnableAsync 开启对异步任务的支持
  2. 实际执行的 Bean 的方法中使用 @Async 注解来声明这个是一个异步任务
@Slf4j
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(3);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("AsyncThread-");
        executor.initialize(); //如果不初始化,导致找到不到执行器
        return executor;
    }

	// 用于捕获异步异常
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    	//return new AsyncExceptionHandler();
        return null;
    }
}


二、实际调用方法


@Async 注解来声明一个异步任务

如下,当然去掉 implements UserService 也是可以的

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Async
    @Override
    public void executeUserInfo(Integer userId) {
        log.info("enter executeUserInfo userId : {}, threadId : {}", userId, Thread.currentThread().getId());
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("exit executeUserInfo userId : {}, threadId : {}", userId, Thread.currentThread().getId());
    }

}


三、测试运行


写一个 controller

@Slf4j
@RestController
@RequestMapping("/async")
public class AsyncController {

    @GetMapping(value = "/test1")
    public String test1() {
        log.info("enter test1, threadId : {}", Thread.currentThread().getId());

        userService.executeUserInfo(1);
        userService.executeUserInfo(2);
        userService.executeUserInfo(3);

        log.info("exit test1, threadId : {}", Thread.currentThread().getId());

        return "123";
    }

}

那么调用这个接口 /async/test1 时,日志如下:
在这里插入图片描述

你可能感兴趣的:(【JavaWeb】)