sharding读写分离强制路由

因为主从同步延迟问题 领导希望可以在某些条件下查询用主库
干就完了
先贴下官网的部分代码

在这里插入图片描述
调用setmaster 会给属性set true
选择主库路由 = 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 再次查询不用注解 默认会走主库 下面是第一次查询和第二次查询打出的日志
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值