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

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

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

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

早些时候,我们曾经在课堂上做一些类似的事情:

@Autowired protected AsyncTaskExecutor executor;

然后

executor.submit(<Some Runnable or Callable task>)

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

我尝试在互联网上搜索很多,但无法获得任何东西。

有人可以提供同样的例子吗?


答案 1

下面是一个使用示例:@Async

@Async
void doSomething() {
    // this will be executed asynchronously
}

现在从另一个类调用该方法,它将异步运行。如果需要返回值,请使用Future

@Async
Future<String> returnSomething(int i) {
    // this will be executed asynchronously
}

和 之间的关系是使用幕后。从文档中:@AsyncTaskExecutor@AsyncTaskExecutor

默认情况下,在方法上指定@Async时,将使用的执行器是提供给“注释驱动”元素的执行器,如上所述。但是,当需要指示在执行给定方法时应使用默认值以外的执行器时,可以使用@Async注释的 value 属性。

因此,要设置默认执行器,请将其添加到您的spring配置中

<task:annotation-driven executor="myExecutor" />

或者使用特定的执行器进行一次性使用尝试

@Async("otherExecutor")

查看 http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support-async


答案 2

完整示例

  1. 配置弹簧

    @Configuration        
    @EnableAsync        
    @ComponentScan("com.async")
    public class AppConfig {
    
        @Bean
        public AsyncManager asyncManger() {
            return new AsyncManager();
        }
    
        @Bean
        public AsyncExecutor asyncExecutor() {
            return new AsyncExecutor();
        }
    }
    
  2. 执行器类已创建,执行器我已创建,以便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;
        }
    }
    
  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) {
            }
    
        }
    }
    
  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());
        }
    }
    
  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;
        }
    
    }
    
  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();
        }
    }
    

推荐