Spring3中提供了一个功能,就是在一个方法上添加注解,调用这个方法的时候自动在线程池中异步话执行。
由于老系统暂时无法升级到spring的3版本,所以翻了一下Spring3中的实现代码。
Spring3中总体就是Spring的AOP和Schema,这两个方式,至于Spring3中注解异步化的使用,这里就不介绍了。
实现思路:
1、搞一个注解来做标志位(就是添加了这个注解,方法自动异步化);
2、用Aspect来处理注解;
3、系统直接使用;
1、注解代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package
org.iamzhongyong.framework;
import
java.lang.annotation.ElementType;
import
java.lang.annotation.Retention;
import
java.lang.annotation.RetentionPolicy;
import
java.lang.annotation.Target;
/**
* 自定义的注解,添加了这个注解之后,方法执行的时候会异步来执行
* @author bixiao.zy
*/
@Target
({ElementType.METHOD, ElementType.TYPE})
@Retention
(RetentionPolicy.RUNTIME)
public
@interface
OrgAsync {
String value()
default
""
;
}
|
2、AOP的代码实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
package
org.iamzhongyong.framework;
import
java.util.concurrent.ArrayBlockingQueue;
import
java.util.concurrent.Callable;
import
java.util.concurrent.ExecutorService;
import
java.util.concurrent.Future;
import
java.util.concurrent.ThreadPoolExecutor;
import
java.util.concurrent.TimeUnit;
import
org.aspectj.lang.ProceedingJoinPoint;
import
org.aspectj.lang.annotation.Around;
import
org.aspectj.lang.annotation.Aspect;
/**
* 异步话执行含有@OrgAsync注解的方法
* @author bixiao.zy
*/
@Aspect
public
class
OrgAsyncAspect {
/**
* 自定义的线程池
*/
private
static
ExecutorService executor =
new
ThreadPoolExecutor(
10
,
15
,
2000
,
TimeUnit.SECONDS,
new
ArrayBlockingQueue<Runnable>(
12
),
new
AsyncThreadFactory());
/**
* 1、处理注解,也就是只有OrgAsync这个注解的方法才会起作用
* 2、采用Aspect的环绕增强,然后ProceedingJoinPoint来实现代理的调用
* 3、线程池执行,提交方法
* @param joinPoint
* @return
* @throws Throwable
*/
@Around
(
"@annotation(org.iamzhongyong.framework.OrgAsync)"
)
public
Object asyncExecutor(
final
ProceedingJoinPoint joinPoint)
throws
Throwable {
Future<?> result = executor.submit(
new
Callable<Object>() {
public
Object call()
throws
Exception {
Object result =
null
;
try
{
result = joinPoint.proceed();
if
(result
instanceof
Future){
return
((Future<?>) result).get();
}
}
catch
(Throwable e) {
//
}
return
result;
}
});
return
result.get();
}
}
|
3、如何使用
第一步,在Spring的IOC容器中,添加这个标签 <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
(这个是启动Aspect的Schema);
第二部,Spring中集成Aspect是采用IOC的思路,所以需要把方法的增强bean添加进来
(<bean id="aysncAspect" class="org.iamzhongyong.framework.OrgAsyncAspect"></bean>);
不足之处:
1、暂时线程池无法满足自定义coreSize和maxSize;
代码地址:https://github.com/iamzhongyong/async