Springboot里asnync修饰

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());
    }


}
posted @   SpecialSpeculator  阅读(72)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示