• 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());
        }
    
    
    }
    
    原创:做时间的朋友
  • 相关阅读:
    Appium+python自动化3-启动淘宝app
    Appium+python自动化2-环境搭建(下)
    Appium+python自动化1-环境搭建(上)
    postman提取返回值
    Android studio(AS)的下载和安装
    monkey的安装和配置
    配置自己的CentOS7服务器
    mac-homebrew安装太慢
    vue.js中祖孙通信之provide与inject
    nginx location 以及 proxy_pass 的几种情况 以/结尾的问题
  • 原文地址:https://www.cnblogs.com/PythonOrg/p/15493240.html
Copyright © 2020-2023  润新知