使用Spring的@Async注解实现方法的异步执行

Spring为任务调度与异步方法执行提供了注解支持。通过在方法上设置@Async注解,可使得方法被异步调用。也就是说调用者会在调用时立即返回,而被调用方法的实际执行是交给Spring的TaskExecutor来完成。

Spring异步配置

<!-- 异步配置 -->
<task:annotation-driven executor="myExecutor"/>

<task:executor id="myExecutor" pool-size="5-25" queue-capacity="100" rejection-policy="CALLER_RUNS"/>

同时在xml的配置文件中要增加标签的定义

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task-4.1.xsd">

使用@Async实现异步执行

@Service
public class APILogServiceImpl implements IAPILogService {

@Async
    public void saveAPILog(String taskId, String accountId, String accountName, String apiId, String apiUrl, String parameter,
            String result) {
            ......
    }
}

这样在其他地方调用该方法的时候就可以实现异步执行

//记录查询日志
apiLogService.saveAPILog(taskId, accountId, accountName, apiId, url, parameter, JSONObject.toJSONString(result));

猜你喜欢

转载自blog.csdn.net/shiyong1949/article/details/80857293