Spring 3:如何从TaskExecutor调用@Async注释方法

tar*_*res 12 java spring multithreading asynchronous spring-mvc

我是Spring的异步任务执行新手,所以如果这听起来像个愚蠢的问题,请原谅我.

我读到@Async注释是从Spring 3.x开始在方法级别引入的,该方法的调用将异步发生.我还读到我们可以在spring配置文件中配置ThreadPoolTask​​Executor.

我无法理解的是,如何从tak执行器调用@Async注释方法让我们假设--AsyncTaskExecutor

早些时候我们曾经做过类似的事情:

@Autowired protected AsyncTaskExecutor executor;
Run Code Online (Sandbox Code Playgroud)

然后

executor.submit(<Some Runnable or Callable task>)
Run Code Online (Sandbox Code Playgroud)

我无法理解@Async注释方法和TaskExecutor之间的关系.

我尝试在互联网上搜索很多但却无法得到任何相关信息.

有人可以为此提供一个例子.

Pla*_*nky 30

这是一个@Async使用示例:

@Async
void doSomething() {
    // this will be executed asynchronously
}
Run Code Online (Sandbox Code Playgroud)

现在从另一个类调用该方法,它将异步运行.如果你想要一个返回值,请使用aFuture

@Async
Future<String> returnSomething(int i) {
    // this will be executed asynchronously
}
Run Code Online (Sandbox Code Playgroud)

之间的关系@Async,并TaskExecutor@Async使用了TaskExecutor幕后.来自文档:

默认情况下,在方法上指定@Async时,将使用的执行程序是提供给"注释驱动"元素的执行程序,如上所述.但是,当需要指示在执行给定方法时应该使用除默认值之外的执行程序时,可以使用@Async批注的value属性.

因此,要设置默认执行程序,请将其添加到spring配置中

<task:annotation-driven executor="myExecutor" />
Run Code Online (Sandbox Code Playgroud)

或者使用特定的执行程序进行单次使用尝试

@Async("otherExecutor")
Run Code Online (Sandbox Code Playgroud)

请参阅http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support-async


Kum*_*hek 5

完整示例

  1. 配置弹簧

    @Configuration        
    @EnableAsync        
    @ComponentScan("com.async")
    public class AppConfig {
    
        @Bean
        public AsyncManager asyncManger() {
            return new AsyncManager();
        }
    
        @Bean
        public AsyncExecutor asyncExecutor() {
            return new AsyncExecutor();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 已创建 Executor 类,我已创建 Executor 以便 spring 负责线程管理。

    public class AsyncExecutor extends AsyncConfigurerSupport {
    
        @Override
        public Executor getAsyncExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(2);
            executor.setMaxPoolSize(2);
            executor.setQueueCapacity(500);
            executor.setThreadNamePrefix("Violation-");
            executor.initialize();
            return executor;
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 创建经理。

    public class AsyncManager {
    
        @Autowired
        private AsyncService asyncService;
    
        public void doAsyncTask(){
            try {
                Map<Long, ViolationDetails> violation = asyncService.getViolation();
                if(!org.springframework.util.CollectionUtils.isEmpty(violation)){
                    violation.entrySet().forEach( violationEntry -> {System.out.println(violationEntry.getKey() +"" +violationEntry.getValue());});
                }
                System.out.println("do some async task");
            } catch (Exception e) {
            }
    
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 配置您的服务类。

    @Service
    public class AsyncService {
    
        @Autowired
        private AsyncExecutor asyncExecutor;
    
        @Async
        public Map<Long,ViolationDetails> getViolation() {
            // TODO Auto-generated method stub
            List<Long> list = Arrays.asList(100l,200l,300l,400l,500l,600l,700l);
            Executor executor = asyncExecutor.getAsyncExecutor();
            Map<Long,ViolationDetails>  returnMap = new HashMap<>();
            for(Long estCode : list){
                ViolationDetails violationDetails = new ViolationDetails(estCode);
                returnMap.put(estCode, violationDetails);
                executor.execute((Runnable)new ViolationWorker(violationDetails));
            }
            return returnMap;       
        }
    }
    class ViolationWorker implements Runnable{
    
        private ViolationDetails violationDetails;
    
        public ViolationWorker(ViolationDetails violationDetails){
            this.violationDetails = violationDetails;
        }
    
        @Override
        public void run() {
            violationDetails.setViolation(System.currentTimeMillis());
            System.out.println(violationDetails.getEstablishmentID() + "    " + violationDetails.getViolation());
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  5. 模型。

    public class ViolationDetails {
        private long establishmentID;
        private long violation;
    
    
        public ViolationDetails(long establishmentID){
            this.establishmentID = establishmentID;
        }
    
        public long getEstablishmentID() {
            return establishmentID;
        }
        public void setEstablishmentID(long establishmentID) {
            this.establishmentID = establishmentID;
        }
        public long getViolation() {
            return violation;
        }
        public void setViolation(long violation) {
            this.violation = violation;
        }
    
    }
    
    Run Code Online (Sandbox Code Playgroud)
  6. 测试运行

    public class AppTest {
        public static void main(String[] args) throws SQLException {
            AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
            ctx.register(AppConfig.class);
            ctx.refresh();
    
            AsyncManager task= ctx.getBean(AsyncManager.class);
            task.doAsyncTask();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)