原创

Select强制走主库

走主库标志位

/**
* 读数据走主库工具类
*
* @author 木杉
* @classname MybatisMasterRouteUtils
* @date 2023/2/10 9:20
*/
public final class MybatisMasterRouteUtils {

private MybatisMasterRouteUtils(){}

/**
* 本地线程
*/
private final static ThreadLocal<Boolean> threadLocal = new ThreadLocal<>();

/**
* 从主库读取数据
*
* @methodName activityReadMasterRoute
* @date 2023/2/10 9:23
* @author 木杉
*/
public static void activityReadMasterRoute(){
threadLocal.set(true);
}

/**
* 获取是否读主库状态
*
* @methodName getReadMasterRoute
* @date 2023/2/10 9:25
* @author 木杉
*/
public static Boolean getReadMasterRoute(){
Boolean flag = threadLocal.get();
flag = (flag == null ? false : flag);
return flag;
}

/**
* 停止从主库读取数据
*
* @methodName stopReadMasterRoute
* @date 2023/2/10 9:23
* @author 木杉
*/
public static void stopReadMasterRoute(){
threadLocal.remove();
}
}

Mybatis拦截器工具类

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;

/**
* Mybatis拦截器工具类
*
* @author 木杉
* @classname MybatisInterceptorUtils
* @date 2023/2/10 9:11
*/
public final class MybatisInterceptorUtils {

private static int MAPPED_STATEMENT_INDEX = 0;
private static int PARAMETER_INDEX = 1;
private static int ROWBOUNDS_INDEX = 2;
private static int RESULT_HANDLER_INDEX = 3;

private MybatisInterceptorUtils(){}

/**
* 获取sql语句
* @param invocation
* @return
*/
public static String getSqlByInvocation(Invocation invocation) {
final Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[MAPPED_STATEMENT_INDEX];
Object parameterObject = args[PARAMETER_INDEX];
BoundSql boundSql = ms.getBoundSql(parameterObject);
return boundSql.getSql();
}

/**
* 包装sql后,重置到invocation中
* @param invocation
* @param sql
*/
public static Invocation resetSql2Invocation(Invocation invocation, String sql) {
final Object[] args = invocation.getArgs();

MappedStatement statement = (MappedStatement) args[MAPPED_STATEMENT_INDEX];
Object parameterObject = args[PARAMETER_INDEX];
BoundSql boundSql = statement.getBoundSql(parameterObject);
MappedStatement newStatement = newMappedStatement(statement, new MybatisInterceptorUtils.BoundSqlSqlSource(boundSql));
MetaObject msObject = MetaObject.forObject(newStatement, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(),new DefaultReflectorFactory());
msObject.setValue("sqlSource.boundSql.sql", sql);
args[MAPPED_STATEMENT_INDEX] = newStatement;

return invocation;
}

private static MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
MappedStatement.Builder builder =
new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
StringBuilder keyProperties = new StringBuilder();
for (String keyProperty : ms.getKeyProperties()) {
keyProperties.append(keyProperty).append(",");
}
keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
builder.keyProperty(keyProperties.toString());
}
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.resultSetType(ms.getResultSetType());
builder.cache(ms.getCache());
builder.flushCacheRequired(ms.isFlushCacheRequired());
builder.useCache(ms.isUseCache());
return builder.build();
}

/**
* 内部辅助类,包装sql
*/
static class BoundSqlSqlSource implements SqlSource {
private BoundSql boundSql;
public BoundSqlSqlSource(BoundSql boundSql) {
this.boundSql = boundSql;
}
@Override
public BoundSql getBoundSql(Object parameterObject) {
return boundSql;
}
}
}

Mybatis拦截器

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
* mysql拦截器
*
* @author 木杉
* @classname MybatisMasterQueryInterceptor
* @date 2023/2/9 15:23
*/
@Intercepts({
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})})
@Slf4j
@Component
public class MybatisInterceptor implements Interceptor {

/**
* 主库标识
*/
private final static String MASTER_ROUTE_FLAG = "/*master*/";

@Override
public Object intercept(Invocation invocation) throws Throwable {

if (MybatisMasterRouteUtils.getReadMasterRoute()) {
//当前query是否读主库
//获取sql语句
String sql = MybatisInterceptorUtils.getSqlByInvocation(invocation);
sql = MASTER_ROUTE_FLAG + sql;
MybatisInterceptorUtils.resetSql2Invocation(invocation, sql);
}
return invocation.proceed();
}

@Override
public Object plugin(Object target) {
return Interceptor.super.plugin(target);
}

@Override
public void setProperties(Properties properties) {
Interceptor.super.setProperties(properties);
}

}

切面

import java.lang.annotation.*;

/**
* 读数据强制走主库
*
* @author 木杉
* @classname MyBatisReadMasterRoute
* @date 2023/2/13 17:47
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface MyBatisReadMasterRoute {
}
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
* 读数据强制走主库切面
*
* @author 木杉
* @classname UserCheckAspect
* @date 2022/11/21 17:05
*/
@Aspect
@Slf4j
@Component
public class MybatisReadMasterRouteAspectAspect {
@Around("@annotation(myBatisReadMasterRoute)")
public Object checkUser(ProceedingJoinPoint point, MyBatisReadMasterRoute myBatisReadMasterRoute) throws Throwable {
MybatisMasterRouteUtils.activityReadMasterRoute();
Object proceed = null;
try {
proceed = point.proceed();
} finally {
MybatisMasterRouteUtils.stopReadMasterRoute();
}
return proceed;
}
}

示例

LevelUser levelUser = null;
try {
MybatisMasterRouteUtils.activityReadMasterRoute();
//主从库存在同步延迟问题 所以这里走主库查询防止插入多条数据
LambdaQueryWrapper<LevelUser> queryWrapper = Wrappers.lambdaQuery();
queryWrapper.eq(LevelUser::getUserId, userId)
.eq(LevelUser::getDelFlag, LevelUserDelEnums.NORMAL.getDelFlag());
levelUser = levelUserService.getOne(queryWrapper);
} finally {
MybatisMasterRouteUtils.stopReadMasterRoute();
}

一定要finally,防止报错后标志位没有修改,该线程随后的sql操作都会走主库

正文到此结束