因为主从同步延迟问题 领导希望可以在某些条件下查询用主库
干就完了
先贴下官网的部分代码
选择主库路由 = true
代码及思路 因为用多了多数据源 所以像这样选择数据源的马上就想到了AOP+annotation
/**
* @Auther: Lming
* @Date: 2020/6/3 09:46
* @Description:
*/
@Retention(RetentionPolicy.RUNTIME)//运行时保留
@Target(ElementType.METHOD)//作用范围是方法
public @interface SwitchMasterDataSource {
}
/**
* @Auther: Lming
* @Date: 2020/6/3 09:48
* @Description:
*/
@Aspect
@Order(1)
@Component
@Slf4j
public class ForceRouteAspect {
@Pointcut("@annotation(com.*.*.annotation.SwitchMasterDataSource)")
public void switchMaster(){}
@Around(value = "switchMaster()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
Object object = null;
Throwable currentThrowable = null;
Class<?> aClass = joinPoint.getTarget().getClass();
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
String methodName = methodSignature.getName();
Class[] argsClass = methodSignature.getParameterTypes();
HintManager hintManager = HintManager.getInstance();
try {
Method method = aClass.getMethod(methodName, argsClass);
if (method.isAnnotationPresent(SwitchMasterDataSource.class)) {
hintManager.setMasterRouteOnly();
}
object = joinPoint.proceed();
} catch (Throwable throwable) {
log.error("主数据源异常==={}", throwable);
currentThrowable = throwable;
} finally {
hintManager.close();
if (currentThrowable != null) {
throw currentThrowable;
}
}
return object;
}
}
用法示例
@SwitchMasterDataSource
public * get*(String s) {
mapper.find***(s);
return *;
}
环绕切 切前强制用主库 之后close 再次查询不用注解 默认会走主库 下面是第一次查询和第二次查询打出的日志