美文网首页
笔记:Spring Boot-Java Config 自定义异步

笔记:Spring Boot-Java Config 自定义异步

作者: denkbug | 来源:发表于2018-04-01 11:28 被阅读0次
    mvn 创建项目
    mvn archetype:generate -DgroupId=com.denk -DartifactId=task-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
    
    pom.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.denk</groupId>
        <artifactId>task-demo</artifactId>
        <packaging>jar</packaging>
        <version>1.0-SNAPSHOT</version>
        <name>task-demo</name>
        <url>http://maven.apache.org</url>
        <dependencies>
            <!--Web-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
        </dependencies>
    
        <!-- Spring Boot-->
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-dependencies</artifactId>
                    <version>1.5.8.RELEASE</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    </project>
    
    导入IDEA项目结构
    项目结构
    入口类
    package com.denk;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class App {
        public static void main(String[] args) {
            SpringApplication.run(App.class);
        }
    }
    
    控制器
    package com.denk.controller;
    
    import com.denk.service.AsyncService;
    import com.denk.service.CommonService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class DemoController {
        @Autowired
        private CommonService commonService;
        @Autowired
        private AsyncService asyncService;
    
        @RequestMapping("/demo")
        public String demo() {
            commonService.dealCommonService_1();
            asyncService.dealAsyncService_1();
            asyncService.dealAsyncService_2();
            asyncService.dealAsyncService_3();
            commonService.dealCommonService_2();
            return "SUCCESS";
        }
    }
    
    普通业务类
    package com.denk.service;
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class CommonService {
        public void dealCommonService_1() {
            System.out.println("处理普通业务1111...");
        }
    
        public void dealCommonService_2() {
            System.out.println("处理普通业务2222...");
        }
    }
    
    异步业务处理类
    package com.denk.service;
    
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Service;
    
    @Service
    
    public class AsyncService {
    
        @Async("executor_1")
        public void dealAsyncService_1() {
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            System.out.println("处理异步业务111..." + Thread.currentThread().getName());
            throw new IllegalArgumentException("异步业务异常111...");
        }
    
        @Async("executor_2")
        public void dealAsyncService_2() {
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("处理异步业务222..." + Thread.currentThread().getName());
            throw new IllegalArgumentException("异步业务异常222...");
        }
    
        @Async
        public void dealAsyncService_3() {
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("处理异步业务333..." + Thread.currentThread().getName());
            throw new IllegalArgumentException("异步业务异常333...");
        }
    }
    
    配置类
    package com.denk.config;
    
    import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.annotation.AsyncConfigurer;
    import org.springframework.scheduling.annotation.EnableAsync;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
    
    import java.lang.reflect.Method;
    import java.util.concurrent.Executor;
    
    @Configuration
    @EnableAsync
    public class AsyncConfig {
    
        @Bean
        @Qualifier("executor_1")
        public Executor getExecutor_1() {
            ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
            taskExecutor.setCorePoolSize(5);
            taskExecutor.setMaxPoolSize(20);
            taskExecutor.setQueueCapacity(100);
            taskExecutor.setThreadNamePrefix("executor_1_");
            taskExecutor.initialize();
            return taskExecutor;
        }
    
        @Bean
        @Qualifier("executor_2")
        public Executor getExecutor_2() {
            ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
            taskExecutor.setCorePoolSize(10);
            taskExecutor.setMaxPoolSize(40);
            taskExecutor.setQueueCapacity(200);
            taskExecutor.setThreadNamePrefix("executor_2_");
            taskExecutor.initialize();
            return taskExecutor;
        }
    
        @Bean
        public AsyncConfigurer getAsyncConfig() {
            return new AsyncConfigurer() {
                public Executor getAsyncExecutor() {
                    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
                    taskExecutor.setCorePoolSize(2);
                    taskExecutor.setMaxPoolSize(5);
                    taskExecutor.setQueueCapacity(10);
                    taskExecutor.setThreadNamePrefix("executor_default_");
                    taskExecutor.initialize();
                    return taskExecutor;
                }
    
                public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
                    return new AsyncUncaughtExceptionHandler() {
                        public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
                            System.out.println("捕获异步异常...#methodName:" + method.getName() +
                                    "#objectsLength:" + objects.length +
                                    "#throwable:" + throwable.toString());
                        }
                    };
                }
            };
        }
    }
    
    说明
    1. 配置类中的@Bean AsyncConfigurer是默认配置,没有指明Executor的@Async默认使用其定义的Executor,以及所有的异步异常在其定义的AsyncUncaughtExceptionHandler被捕获
    2. 多线程池使用@Qualifier("executor_1")标识,由@Async("executor_1")配套使用
    3. 浏览器访问http://localhost:8080/demo,查看控制台打印结果

    相关文章

      网友评论

          本文标题:笔记:Spring Boot-Java Config 自定义异步

          本文链接:https://www.haomeiwen.com/subject/eapocftx.html