spring 开启异步支持

本文中使用的spring版本是 4.3.10 release版,为此时最新发布版.html

本文中的内容在spring文档的34章4节,地址为 http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#scheduling-annotation-support-exception.java

##使用java配置开启异步支持spring

@Configuration
@EnableAsync
@EnableScheduling
public class AppConfig {
}
  • @Configuration 标志这是一个spring的配置类异步

  • @EnableAsync 标志异步支持开始.net

  • @EnableScheduling 标志着定时任务开始线程

##使用xml开始异步支持code

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor" pool-size="5"/>
<task:scheduler id="myScheduler" pool-size="10"/>
</beans>
  • 设置了task的执行器,id为'myExecutor',线程池容量为5;xml

  • 设置了定时任务的执行器,id为'myScheduler',线程池容量为10;htm

在事件中使用异步方法进程

@EventListener
    @Async
    public void handleEvent2(EventEvent event) {

        System.out.println("异步输出问题!!");
    }
  • @EventListener,标志这是一个事件监听器

  • @Async 标志这是一个异步方法,该方法将做为守护进程运行.

通常异步方法的返回值应该是java.util.concurrent.Future类型或 Spring 4.2新增的 org.springframework.util.concurrent.ListenableFuture 还有JDK 8的 java.util.concurrent.CompletableFuture类型

目前spring的事件异步处理方法不支持任何返回值.

相关文章
相关标签/搜索