Async注解
1.自定义使用的线程池
@EnableAsync
@Configuration
public class AsyncConfig implements AsyncConfigurer {
@Bean("customAsyncPool")
@Override
public ThreadPoolExecutor getAsyncExecutor(){
return ThreadUtils.newDaemonFixedThreadPool(Runtime.getRuntime().availableProcessors(),"CUSTOM-ASYNC-POOL");
}
/**
* 捕获无返回值的线程方法异常
* @return
*/
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new CustomAsyncExceptionHandler();
}
}
指定线程池中异常捕获类CustomAsyncExceptionHandler
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(CustomAsyncExceptionHandler.class);
@Override
public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
logger.error("异常捕获-----------------");
logger.error("Exception message - " + throwable.getMessage() );
for (Object param:objects) {
logger.error("Parameter value - " + param);
}
logger.error("异常捕获-----------------");
}
}
2.修饰异步方法
特别注意:
@Async注解修饰的方法一定要在@Service修饰的服务类中使用,controller调用才会达到异步效果,被同级的service方法调用不会达到异步效果
@Service
public class SleepService {
private static final Logger logger = LoggerFactory.getLogger(SleepService.class);
@Async("customAsyncPool")
public Future<String> sleep(){
logger.info("sleep start");
ThreadUtils.sleep(1000 * 10);
logger.info("sleep finish");
return new AsyncResult<>("success");
}
}
controller调用
@Api(tags="测试Controller")
@RestController
@RequestMapping("test")
public class TestController extends BaseController {
@Autowired
SleepService sleepService;
private String ip;
@GetMapping("/heartbeat")
public String hello() {
// ThreadUtils.sleep(5000);
String msg = "FireEye ip: %s time: %s";
sleepService.sleep();
return String.format(msg, ip, LocalDateTime.now().toString());
}
}