package cn.ksource.core.dsource;
|
|
import java.lang.reflect.Method;
|
import java.util.ArrayList;
|
import java.util.List;
|
|
import org.springframework.aop.AfterReturningAdvice;
|
import org.springframework.aop.MethodBeforeAdvice;
|
import org.springframework.aop.ThrowsAdvice;
|
|
import cn.ksource.core.util.ConvertUtil;
|
import cn.ksource.core.util.StringUtil;
|
|
public class DataSourceAspect implements MethodBeforeAdvice,AfterReturningAdvice,ThrowsAdvice {
|
|
/**
|
* 方法和使用数据源key的对应关系
|
*/
|
private List<String> aspectMethodPrefixOrSuffer = new ArrayList<String>();
|
|
private int slaveNum = 0;
|
|
//事务执行方法执行之前被调用
|
@Override
|
public void before(Method method, Object[] args, Object target) throws Throwable {
|
System.out.println("切入点: " + target.getClass().getName() + "类中" + method.getName() + "方法");
|
String methodName = method.getName();
|
for(String value : aspectMethodPrefixOrSuffer) {
|
if(isMatch(methodName, value)) {
|
System.out.println("切换到: master");
|
DataSourceSwitcher.setMaster();
|
return;
|
}
|
}
|
|
//随机选择slave
|
String randomNum = StringUtil.randomNumber(6);
|
int totalNum = 0;
|
for(int i=0; i<randomNum.length(); i++) {
|
char c = randomNum.charAt(i);
|
int num = ConvertUtil.obj2Int(c);
|
totalNum += num;
|
}
|
|
int num = totalNum%slaveNum;
|
|
System.out.println("切换到: slave"+num);
|
DataSourceSwitcher.setSlave(num);
|
}
|
|
|
|
|
private boolean isMatch(String methodName, String value) {
|
return methodName.startsWith(value) || methodName.endsWith(value);
|
}
|
|
|
|
|
//事务方法执行完之后被调用
|
public void afterReturning(Object arg0, Method method, Object[] args, Object target) throws Throwable {
|
}
|
|
// 抛出Exception之后被调用
|
public void afterThrowing(Method method, Object[] args, Object target, Exception ex) throws Throwable {
|
DataSourceSwitcher.setSlave(0);
|
System.out.println("出现异常,切换到: slave");
|
}
|
|
|
public List<String> getAspectMethodPrefixOrSuffer() {
|
return aspectMethodPrefixOrSuffer;
|
}
|
|
public void setAspectMethodPrefixOrSuffer(
|
List<String> aspectMethodPrefixOrSuffer) {
|
this.aspectMethodPrefixOrSuffer = aspectMethodPrefixOrSuffer;
|
}
|
|
|
|
|
public int getSlaveNum() {
|
return slaveNum;
|
}
|
|
|
|
|
public void setSlaveNum(int slaveNum) {
|
this.slaveNum = slaveNum;
|
}
|
|
|
|
}
|