biz-context:
<!-- 通知代码 -->
<bean id="methodConcurrencyControlAroundAdvice" class="com.palic.elis.lcs.common.aop.concurrency.MethodConcurrencyControlAroundAdvice"/>
<!-- 切入点 -->
<bean id="methodConcurrencyControlPointcut" class="com.palic.elis.lcs.common.aop.concurrency.MethodConcurrencyControlPointcut">
<property name="methodNames">
<list>
<value>examLevelProcessByEoa</value>
<value>qualityScoreConfirmByEoa</value>
<value>getEOAValidateCode</value>
</list>
</property>
</bean>
<!-- 连接点 :包括了调用通知操作的时机pointcut,和通知操作本身advice-->
<bean id="methodConcurrencyControlPointcutAdvisor" class="com.palic.elis.lcs.common.aop.concurrency.MethodConcurrencyControlPointcutAdvisor">
<property name="advice">
<ref bean="methodConcurrencyControlAroundAdvice" />
</property>
<property name="pointcut">
<ref bean="methodConcurrencyControlPointcut" />
</property>
</bean>
<!-- 代理类 其target 继承了关联系统 LcsService类,表示关注Service接口调用时使用,此处的拦截器interceptorNames配置的是一个around类型的通知,可以继续添加其他before、after和throwAdvice抛异常通知-->
<bean id="method.concurrency.control.proxy.related" class="com.paic.pafa.app.lwc.core.aop.framework.ProxyFactoryBean">
<property name="target">
<ref bean="com.palic.elis.lcs.pub.relatedsystem.biz.service.RelatedSystemService"/>
</property>
<property name="interceptorNames">
<list>
<value>methodConcurrencyControlPointcutAdvisor</value>
</list>
</property>
</bean>
adicve实现类
public class MethodConcurrencyControlAroundAdvice implements MethodInterceptor {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
DevLog.debug("/******************************方法访问线程控制 日志开始*******************************************/");
//在方法执行前判断当前线程数是否已经达到最大执行线程数,如果已达到则返回相关信息
String methodName = methodInvocation.getMethod().getName();
//将执行方法对应当前线程占有数量+1
ConcurrenceCountUtils.addMethodCurrentTheardNum(methodName);
int maxTheardNum = ConcurrenceCountUtils.getMethodMaxTheardNum(methodName);
int currentTheardNum = ConcurrenceCountUtils.getMethodCurrentTheardNum(methodName);
DevLog.debug(Thread.currentThread().getName()+" 取到当前方法调用线程数为:"+currentTheardNum+" 配置最大线程数为:"+maxTheardNum);
if(currentTheardNum>maxTheardNum){
//当线程数达到最大值时,需要先减少当前线程做的添加数
//System.out.println("当前链接数已到瓶颈,"+Thread.currentThread().getName()+" 不能调用方法:"+methodName);
ConcurrenceCountUtils.lessMethodCurrentTheardNum(methodName);
throw new LcsAppException("当前操作所允许连接数已满,请稍后重试!");
}
Object obj = null;
try{
//around方法必须调用methodInvocation的proceed来调用切入点的本身操作,这样around才知道怎样包围这个切入点
obj = methodInvocation.proceed();
}catch(Exception ex){
//执行方法报错后,释放当前占用线程数
DevLog.debug("方法线程数控制,执行调用方法报错:"+methodName);
ConcurrenceCountUtils.lessMethodCurrentTheardNum(methodName);
throw new LcsBusinessException(ex);
}
//正确执行完方法后,释放当前占用线程数
ConcurrenceCountUtils.lessMethodCurrentTheardNum(methodName);
DevLog.debug("/******************************方法访问线程控制 日志结束*******************************************/");
return obj;
}
}
本文介绍了一种基于Spring AOP的方法级并发控制策略,通过定义切入点、通知操作和代理类,实现对特定方法调用的线程并发数进行限制,避免因线程过多导致的服务不可用。
7536

被折叠的 条评论
为什么被折叠?



