當(dāng)前位置:首頁 > IT技術(shù) > 編程語言 > 正文

Springboot里asnync修飾
2021-11-01 14:32:24

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修飾的服務(wù)類中使用,controller調(diào)用才會(huì)達(dá)到異步效果,被同級(jí)的service方法調(diào)用不會(huì)達(dá)到異步效果

@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調(diào)用

@Api(tags="測(cè)試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());
    }


}

本文摘自 :https://www.cnblogs.com/

開通會(huì)員,享受整站包年服務(wù)立即開通 >