import java.lang.reflect.Method;
import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
* 处理走备库逻辑的注解
*/
@Component
public class SwitchDataBaseInterceptor implements MethodInterceptor {
private final Logger log = LoggerFactory.getLogger(SwitchDataBaseInterceptor.class);
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
SwitchDataBase annotation = getAnnotation(method);
if (annotation == null) {
return invocation.proceed();
}
Object val = null;
if(!ThreadLocalMap.containsKey(GroupDataSourceRouteHelper.DATASOURCE_INDEX)) {
if (annotation.switch2Backup()) {
log.info("query back up DB, method: " + method.getName());
GroupDataSourceRouteHelper.executeByGroupDataSourceIndex(1, true);
} else {
log.info("query primary DB, method: " + method.getName());
GroupDataSourceRouteHelper.executeByGroupDataSourceIndex(0, true);
}
}
try {
val = invocation.proceed();
} catch (Exception e) {
log.info(method.getDeclaringClass().getName() + "." +
invocation.getMethod().getName() + "方法调用失败,arguments:" +
Arrays.toString(invocation.getArguments()));
throw new RuntimeException(e);
} finally {
GroupDataSourceRouteHelper.removeGroupDataSourceIndex();
}
return val;
}
* 找方法上面声明的注解
*/
private SwitchDataBase getAnnotation(Method method) {
if (method.isAnnotationPresent(SwitchDataBase.class)) {
return method.getAnnotation(SwitchDataBase.class);
}
return null;
}
}