欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot+mybatis-plus基于攔截器實(shí)現(xiàn)分表的示例代碼

 更新時(shí)間:2021年11月09日 08:54:14   作者:LL小蝸牛  
本文主要介紹了springboot+mybatis-plus基于攔截器實(shí)現(xiàn)分表,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

前言

最近在工作遇到數(shù)據(jù)量比較多的情況,單表壓力比較大,crud的操作都受到影響,因?yàn)槟承┰?,?xiàng)目上沒(méi)有引入sharding-jdbc這款優(yōu)秀的分表分庫(kù)組件,所以打算簡(jiǎn)單寫(xiě)一個(gè)基于mybatis攔截器的分表實(shí)現(xiàn)

一、設(shè)計(jì)思路

在現(xiàn)有的業(yè)務(wù)場(chǎng)景下,主要實(shí)現(xiàn)的目標(biāo)就是表名的替換,需要解決的問(wèn)題有

  • 如何從執(zhí)行的方法中,獲取對(duì)應(yīng)的sql并解析獲取當(dāng)前執(zhí)行的表名
  • 表名的替換策略來(lái)源,替換規(guī)則
  • 實(shí)體自動(dòng)建表功能

二、實(shí)現(xiàn)思路

針對(duì)第一個(gè)問(wèn)題,我們可以用mybatis提供的攔截器對(duì)sql進(jìn)行處理,并用Druid自帶的sql解析功能實(shí)現(xiàn)表名的獲取

第二個(gè)問(wèn)題是相對(duì)核心的,在攔截器里面,本質(zhì)上是維護(hù)了一個(gè)map,key是原表名,value是替換后的表名,構(gòu)造這個(gè)map可以有不同的方式,目前想到的有這2種

  • threadLocal存儲(chǔ)一個(gè)map,用于攔截器使用
  • 從當(dāng)前方法獲取某個(gè)入?yún)ⅲㄟ^(guò)一些策略來(lái)生成對(duì)應(yīng)的替換后的表名

實(shí)現(xiàn)自動(dòng)建表的功能可以在執(zhí)行sql前,通過(guò)某些規(guī)則獲取用戶的方法,反射進(jìn)行調(diào)用,但這里可能會(huì)存在線程安全問(wèn)題(重復(fù)執(zhí)行建表方法)

三、代碼實(shí)現(xiàn)

首先看看代碼結(jié)構(gòu)

下面是對(duì)應(yīng)的注解

接口描述

這個(gè)接口用于攔截器內(nèi)標(biāo)識(shí)解析的數(shù)據(jù)庫(kù)類(lèi)型,還有一個(gè)checkTableSql是用于檢查是否有對(duì)應(yīng)的表名存在,用于自動(dòng)建表的校驗(yàn)

package com.xl.mphelper.shard;
 
import com.alibaba.druid.DbType;
import com.xl.mphelper.dynamic.DynamicDatasource;
 
import java.util.Collection;
import java.util.Iterator;
 
/**
 * @author tanjl11
 * @date 2021/10/18 16:57
 * 簡(jiǎn)單的分庫(kù)的可以直接用{@link com.xl.mphelper.dynamic.DynamicDataSourceHolder} 自己在業(yè)務(wù)層處理
 * 在{@link DynamicDatasource#getConnection()}獲取鏈接,如果用注解事務(wù)不能保證事務(wù)完整
 * 可以在同一個(gè)數(shù)據(jù)源內(nèi),調(diào){@link com.xl.mphelper.service.CustomServiceImpl#doInTransaction(Runnable)}來(lái)開(kāi)啟一個(gè)事務(wù)
 */
public interface ITableShardDbType {
    /**
     * 數(shù)據(jù)庫(kù)類(lèi)型
     *
     * @return
     */
    DbType getDbType();
 
    /**
     * 必須返回單列,值為表名,傳入的是待建表的值
     * 如果沒(méi)有的話,就不會(huì)走檢查邏輯
     * @param curTableNames
     * @return
     */
    default String getCheckTableSQL(Collection<String> curTableNames) {
        return null;
    }
 
    ;
 
    class MysqlShard implements ITableShardDbType {
 
        private static String DEFAULT_GET_TABLE_SQL = "select TABLE_NAME from information_schema.TABLES where TABLE_NAME in ";
 
        @Override
        public DbType getDbType() {
            return DbType.mysql;
        }
 
        @Override
        public String getCheckTableSQL(Collection<String> curTableNames) {
            StringBuilder tableParam = new StringBuilder("(");
            Iterator<String> iterator = curTableNames.iterator();
            while (iterator.hasNext()) {
                String next = iterator.next();
                tableParam.append("'").append(next).append("'").append(",");
            }
            int i1 = tableParam.lastIndexOf(",");
            tableParam.replace(i1, tableParam.length(), ")");
            return DEFAULT_GET_TABLE_SQL + tableParam;
        }
    }
}

另外一個(gè)接口主要是處理表邏輯,將實(shí)體+邏輯表名映射為實(shí)際的表,默認(rèn)提供三種策略

package com.xl.mphelper.shard;
 
import com.alibaba.druid.support.json.JSONUtils;
import com.xl.mphelper.annonations.TableShardParam;
import org.springframework.util.DigestUtils;
 
import java.nio.charset.StandardCharsets;
/**
 * @author tanjl11
 * @date 2021/10/15 16:18
 */
@FunctionalInterface
public interface ITableShardStrategy<T> {
    /**
     * 通過(guò)實(shí)體獲取表名,可以用 {@link TableShardParam}指定某個(gè)參數(shù),并復(fù)寫(xiě)對(duì)應(yīng)的策略
     * 如果是可迭代的對(duì)象,會(huì)取列表的第一個(gè)參數(shù)作為對(duì)象,所以再進(jìn)入sql前要進(jìn)行分組
     * 也可以使用 {@link TableShardHolder} 進(jìn)行名稱(chēng)替換
     * 優(yōu)先級(jí):TableShardHolder>TableShardParam>參數(shù)第一個(gè)
     *
     * @param tableName
     * @param entity
     * @return
     */
    String routingTable(String tableName, T entity);
 
    class TableShardDefaultStrategy implements ITableShardStrategy {
        @Override
        public String routingTable(String tableName, Object entity) {
            return tableName + "_" + entity.toString();
        }
    }
 
    class CommonStrategy implements ITableShardStrategy<Shardable> {
 
        @Override
        public String routingTable(String tableName, Shardable shardable) {
            return tableName + "_" + shardable.suffix();
        }
    }
 
    class HashStrategy implements ITableShardStrategy {
        @Override
        public String routingTable(String tableName, Object entity) {
            Integer length = TableShardHolder.hashTableLength();
            if (length == null||length==0) {
                throw new IllegalStateException("illegal hash length in TableShardHolder");
            }
            String hashKey=null;
            if (entity instanceof String) {
                hashKey= (String) entity;
            }
            if(entity instanceof Shardable){
                hashKey=((Shardable)entity).suffix();
            }
            if(entity instanceof Number){
                hashKey=entity.toString();
            }
            if(hashKey==null&&entity!=null){
                hashKey= JSONUtils.toJSONString(entity);
            }
            if(hashKey==null){
                throw new IllegalStateException("can not generate hashKey in current param:"+entity);
            }
            String value = DigestUtils.md5DigestAsHex(hashKey.getBytes(StandardCharsets.UTF_8));
            value=value.substring(value.length()-4);
            long hashMod = Long.parseLong(value, 16);
            return tableName+"_"+hashMod % length;
        }
    }
}

shardable接口

package com.xl.mphelper.shard;
 
/**
 * @author tanjl11
 * @date 2021/10/27 17:17
 */
public interface Shardable {
    String suffix();
}

核心組成部分

1.本地線程工具類(lèi)

首先是上面說(shuō)的本地線程,主要是獲取了映射的map,通過(guò)tableName注解來(lái)獲取原表名,并設(shè)置一些屬性來(lái)標(biāo)識(shí)是否走攔截器的邏輯,也包括了hash的一些邏輯

package com.xl.mphelper.shard;
 
import com.baomidou.mybatisplus.annotation.TableName;
import com.xl.mphelper.util.ApplicationContextHolder;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * @author tanjl11
 * @date 2021/10/18 15:18
 * 用于自定義表名,在與sql交互前使用
 * 否則默認(rèn)走攔截器的獲取參數(shù)邏輯
 */
public class TableShardHolder {
    protected static ThreadLocal<Map<String, Object>> HOLDER = ThreadLocal.withInitial(HashMap::new);
    private static String INGORE_FLAG = "##ingore@@";
    private static String HASH_LENGTH = "##hash_length@@";
 
    //默認(rèn)以_拼接
    public static void putVal(Class entityClazz, String suffix) {
        if (entityClazz.isAnnotationPresent(TableName.class)) {
            TableName tableName = (TableName) entityClazz.getAnnotation(TableName.class);
            String value = tableName.value();
            if (value.equals(INGORE_FLAG) || value.equals(HASH_LENGTH)) {
                throw new IllegalStateException("conflict with ignore flag,try another table name");
            }
            //hash策略處理
            String res = value + "_" + suffix;
            if (hashTableLength() != null) {
                ITableShardStrategy tableShardStrategy = TableShardInterceptor.SHARD_STRATEGY.computeIfAbsent(ITableShardStrategy.HashStrategy.class, e -> (ITableShardStrategy) ApplicationContextHolder.getBeanOrInstance(e));
                res = tableShardStrategy.routingTable(value, suffix);
            }
            HOLDER.get().put(value, res);
        }
    }
 
    public static void ignore() {
        HOLDER.get().put(INGORE_FLAG, "");
    }
 
    protected static boolean isIgnore() {
        return HOLDER.get().containsKey(INGORE_FLAG);
    }
 
    public static void resetIgnore() {
        HOLDER.get().remove(INGORE_FLAG);
    }
 
    public static void remove(Class entityClazz) {
        if (entityClazz.isAnnotationPresent(TableName.class)) {
            TableName tableName = (TableName) entityClazz.getAnnotation(TableName.class);
            String value = tableName.value();
            HOLDER.get().remove(value);
        }
    }
 
    protected static String getReplaceName(String tableName) {
        return (String) HOLDER.get().get(tableName);
    }
 
    protected static boolean containTable(String tableName) {
        return HOLDER.get().containsKey(tableName);
    }
 
    protected static boolean hasVal() {
        return HOLDER.get() != null && !HOLDER.get().isEmpty();
    }
 
    public static void clearAll() {
        HOLDER.remove();
    }
 
    public static void hashTableLength(int length) {
        HOLDER.get().put(HASH_LENGTH, length);
    }
 
    protected static Integer hashTableLength() {
        return (Integer) HOLDER.get().get(HASH_LENGTH);
    }
 
    public static void clearHashTableLength() {
        HOLDER.get().remove(HASH_LENGTH);
    }
}

2.注解部分

TableShardParam 作用于方法參數(shù)上面,對(duì)應(yīng)的值會(huì)傳入對(duì)應(yīng)的分表方法里面,如果啟用了hash分表,會(huì)自動(dòng)替換成hash策略

package com.xl.mphelper.annonations;
 
import com.xl.mphelper.shard.ITableShardStrategy;
 
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
/**
 * @author tanjl11
 * @date 2021/10/15 17:56
 * 這個(gè)策略比類(lèi)上的要高
 * 用于方法參數(shù)
 */
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface TableShardParam {
    //獲取表名的策略
    Class<? extends ITableShardStrategy> shardStrategy() default ITableShardStrategy.TableShardDefaultStrategy.class;
 
    int hashTableLength() default -1;
 
    boolean enableHash() default false;
}

TableShard,作用于mapper上面,主要描述了自動(dòng)建表信息和獲取表映射的信息,還有獲取當(dāng)前方法的信息,同樣也對(duì)常用的hash進(jìn)行處理

package com.xl.mphelper.annonations;
 
import com.xl.mphelper.shard.ExecBaseMethod;
import com.xl.mphelper.shard.ITableShardDbType;
import com.xl.mphelper.shard.ITableShardStrategy;
 
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
/**
 * @author tanjl11
 * @date 2021/10/15 16:13
 * 作用于mapper上面
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TableShard {
    //是否自動(dòng)建表
    boolean enableCreateTable() default false;
 
    //創(chuàng)建表方法
    String createTableMethod() default "";
 
 
    //獲取表名的策略
    Class<? extends ITableShardStrategy> shardStrategy() default ITableShardStrategy.CommonStrategy.class;
 
    //是否啟用hash策略,-1不啟用,其他作為分表的數(shù)量
    int hashTableLength() default -1;
 
    //默認(rèn)使用的db策略
    Class<? extends ITableShardDbType> dbType() default ITableShardDbType.MysqlShard.class;
 
    //選取方法的策略,用到分頁(yè)組件時(shí)需額外注意
    Class<? extends ExecBaseMethod> execMethodStrategy() default ExecBaseMethod.class;
}

獲取方法的類(lèi),對(duì)應(yīng)上面的execMethodStrategy,主要是判斷當(dāng)前方法是否需要分表以及給出對(duì)應(yīng)方法的參數(shù)(項(xiàng)目上用了pagehelper,count的時(shí)候會(huì)默認(rèn)帶個(gè)后綴,所以是額外處理),下面是公共處理

package com.xl.mphelper.shard;
 
import com.xl.mphelper.annonations.TableShardIgnore;
 
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
 
/**
 * @author tanjl11
 * @date 2021/10/26 18:43
 * 當(dāng)找不到方法時(shí)候,可能是分頁(yè)類(lèi)型的,需要額外處理
 */
public class ExecBaseMethod {
 
    protected MethodInfo genMethodInfo(Method[] candidateMethods, String curMethodName) {
        Method curMethod = null;
        for (Method method : candidateMethods) {
            if (method.getName().equals(curMethodName)) {
                curMethod = method;
                break;
            }
        }
        if (curMethod == null) {
            MethodInfo methodInfo = new MethodInfo();
            methodInfo.shouldIgnore = true;
            return methodInfo;
        }
        boolean shouldIgnore = curMethod.isAnnotationPresent(TableShardIgnore.class);
        MethodInfo methodInfo = new MethodInfo();
        methodInfo.shouldIgnore = shouldIgnore;
        methodInfo.parameters = curMethod.getParameters();
        return methodInfo;
    }
 
    public static class MethodInfo {
        protected boolean shouldIgnore;
        protected Parameter[] parameters;
    }
}

還有個(gè)注解就是作用于方法上,標(biāo)識(shí)該方法需要忽略,不走分表攔截的邏輯

3.攔截器實(shí)現(xiàn)

定義了幾個(gè)緩存類(lèi)

分別是緩存mapper、分表策略、數(shù)據(jù)庫(kù)類(lèi)型、已經(jīng)處理過(guò)的表(自動(dòng)建表邏輯)

 private static final Map<String, Class> MAPPER_CLASS_CACHE = new ConcurrentHashMap<>();
    private static final Map<Class, ITableShardStrategy> SHARD_STRATEGY = new ConcurrentHashMap<>();
    private static final Map<Class, ITableShardDbType> SHARD_DB = new ConcurrentHashMap<>();
 
    private static final Set<String> HANDLED_TABLE = new ConcurrentSkipListSet<>();

首先需要通過(guò)StatmentHandler來(lái)獲取boundSql、MappedStatement對(duì)象

routingStatementHandler里面有三種statementHandler,他們都繼承于BaseStatementHandler

這個(gè)類(lèi)里面就有boundSql對(duì)象

boundSql對(duì)象可以獲取執(zhí)行的sql,還有當(dāng)前方法的值

MappedStatement對(duì)象主要是mapper方法的一個(gè)封裝,包括入?yún)?、返回結(jié)果等

關(guān)系圖如下,routingStatementHandler是一個(gè)入口,根據(jù)不同的type用不同的handler進(jìn)行處理

mybatis會(huì)用動(dòng)態(tài)代理來(lái)創(chuàng)建一個(gè)invocation對(duì)象給到攔截器

上面大概說(shuō)明了攔截器是怎么獲取到當(dāng)前方法的參數(shù)的,以及myabtis提供了metaObject來(lái)獲取BoundSql、MappedStatement 來(lái)獲取當(dāng)前執(zhí)行的sql,當(dāng)前執(zhí)行的方法等信息

這時(shí)候我們可以確定,我們攔截器的攔截范圍

  @Override
    public Object plugin(Object target) {
        if (target instanceof RoutingStatementHandler) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

以及獲取上面兩個(gè)關(guān)鍵對(duì)象的方法

RoutingStatementHandler statementHandler = (RoutingStatementHandler) invocation.getTarget();
        //獲取
        MetaObject metaObject = MetaObject.forObject(statementHandler, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, REFLECTOR_FACTORY);
        BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");

MappedStatement的ID就是mapper里面一個(gè)方法的標(biāo)識(shí)

org.apache.ibatis.builder.annotation.MapperAnnotationBuilder#parseStatement

上面的方法里面標(biāo)識(shí)了他的組成,就是mapperClass的名稱(chēng)+方法名

通過(guò)上述規(guī)則,解析id來(lái)獲取對(duì)應(yīng)的mapper名稱(chēng)

 private Class<? extends BaseMapper> getMapperClass(MappedStatement mappedStatement) {
        String id = mappedStatement.getId();
        //mapperClass
        String className = id.substring(0, id.lastIndexOf("."));
        return MAPPER_CLASS_CACHE.computeIfAbsent(className, name -> {
            try {
                return Class.forName(name);
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException(e);
            }
        });
    }

獲取到mapper的class之后,獲取對(duì)應(yīng)的注解,對(duì)于判斷是否需要走攔截器的邏輯,用到了上面獲取方法信息的ExecBaseMethod,該接口返回了是否需要執(zhí)行邏輯,以及當(dāng)前方法的參數(shù)列表

 private ExecBaseMethod.MethodInfo getExecMethod(MappedStatement mappedStatement, Class mapperClass, TableShard annotation) {
        String id = mappedStatement.getId();
        //methodName
        String methodName = id.substring(id.lastIndexOf(".") + 1);
        final Method[] methods = mapperClass.getMethods();
        ExecBaseMethod execMethod = (ExecBaseMethod) getObjectByClass(annotation.execMethodStrategy());
        return execMethod.genMethodInfo(methods, methodName);
    }

這時(shí)候已經(jīng)獲取到了TableShard注解、執(zhí)行方法的信息,然后可以結(jié)合上面獲取的BoundSql對(duì)象,來(lái)解析獲取對(duì)應(yīng)的表名

這里插個(gè)題外話,下面這段代碼是獲取一個(gè)解析sql的處理器

SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(dbType);

當(dāng)時(shí)也想用一個(gè)靜態(tài)map緩存起來(lái),但是線上運(yùn)行時(shí)候發(fā)現(xiàn)oom,后面分析一下原來(lái)這個(gè)visitor每次解析sql之后,都會(huì)產(chǎn)生大量跟預(yù)編譯相關(guān)SLVariantRefExpr對(duì)象,所以導(dǎo)致緩存不斷變大缺無(wú)法回收,后面改為在方法內(nèi)執(zhí)行

private Set<String> getTableNames(BoundSql boundSql, TableShard shard) {
        Class<? extends ITableShardDbType> shardDb = shard.dbType();
        ITableShardDbType iTableShardDb = SHARD_DB.computeIfAbsent(shardDb, e -> (ITableShardDbType) getObjectByClass(shardDb));
        //獲取sql語(yǔ)句
        String originSql = boundSql.getSql();
        DbType dbType = iTableShardDb.getDbType();
        SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(dbType);
        List<SQLStatement> stmtList = SQLUtils.parseStatements(originSql, dbType);
        Set<String> tableNames = new HashSet<>();
        for (int i = 0; i < stmtList.size(); i++) {
            SQLStatement stmt = stmtList.get(i);
            stmt.accept(visitor);
            Map<TableStat.Name, TableStat> tables = visitor.getTables();
            for (TableStat.Name name : tables.keySet()) {
                tableNames.add(name.getName());
            }
        }
        return tableNames;
    }

此時(shí)我們已經(jīng)獲取了表名,可以準(zhǔn)備構(gòu)造上面說(shuō)的映射map了,在此之前先說(shuō)明下建表邏輯

拿出一個(gè)連接,執(zhí)行用戶的方法,可以看到我們當(dāng)前攔截的方法prepare,第一個(gè)參數(shù)就是連接

這個(gè)時(shí)候我們可以直接拿鏈接進(jìn)行建表操作(只針對(duì)insert操作才進(jìn)行建表判斷),不過(guò)出于性能考慮,這里設(shè)置了兩個(gè)校驗(yàn),第一個(gè)是判斷本地內(nèi)存是否已經(jīng)處理了這些表,第二個(gè)是判斷數(shù)據(jù)庫(kù)里面是否有了這些表,校驗(yàn)通過(guò)后,才會(huì)執(zhí)行建表的方法,但如果并發(fā)比較高的話,還是可能有多個(gè)線程同時(shí)走到了建表方法,所以這里建議建表方法使用create if not exists語(yǔ)法

private void handleTableCreate(Invocation invocation,  Class<? extends BaseMapper> mapperClass, Map<String, String> routingTableMap, TableShard annotation) throws SQLException {
        //代表已經(jīng)處理了這些表
        boolean exec = false;
        Collection<String> curTableValues = routingTableMap.values();
        for (String value : curTableValues) {
            if (!HANDLED_TABLE.contains(value)) {
                exec = true;
                break;
            }
        }
        if (!exec) {
            return;
        }
        String tableMethod = annotation.createTableMethod();
        Method createTableMethod = null;
        if (tableMethod.length() > 0) {
            createTableMethod = ReflectionUtils.findMethod(mapperClass, tableMethod);
        }
        //把建表語(yǔ)句對(duì)應(yīng)的sql進(jìn)行表名的替換,如果該方法有ignore注解,不會(huì)進(jìn)行調(diào)用
        if (createTableMethod != null && !createTableMethod.isAnnotationPresent(TableShardIgnore.class)) {
            SqlSessionFactory sessionFactory = ApplicationContextHolder.getBean(SqlSessionFactory.class);
            String methodPath = mapperClass.getName() + "." + tableMethod;
            Configuration configuration = sessionFactory.getConfiguration();
            String createTableSql = configuration.getMappedStatement(methodPath).getBoundSql("delegate.boundSql").getSql();
            //判斷是否已經(jīng)有這個(gè)表
            Set<String> prepareHandledTable = new HashSet<>();
            for (Map.Entry<String, String> entry : routingTableMap.entrySet()) {
                if (createTableSql.contains(entry.getKey())) {
                    prepareHandledTable.add(entry.getValue());
                    createTableSql = createTableSql.replaceAll(entry.getKey(), entry.getValue());
                }
            }
            //獲取一個(gè)連接
            Connection conn = (Connection) invocation.getArgs()[0];
            boolean preAutoCommitState = conn.getAutoCommit();
            conn.setAutoCommit(false);
            Class<? extends ITableShardDbType> shardDb = annotation.dbType();
            ITableShardDbType iTableShardDb = SHARD_DB.computeIfAbsent(shardDb, e -> (ITableShardDbType) getObjectByClass(shardDb));
            //如果沒(méi)有檢查sql,默認(rèn)已經(jīng)建表
            String checkTableSQL = iTableShardDb.getCheckTableSQL(curTableValues);
            boolean contains = existsTable(conn, curTableValues, checkTableSQL);
            if (contains) {
                conn.setAutoCommit(preAutoCommitState);
                HANDLED_TABLE.addAll(curTableValues);
                return;
            }
            try (PreparedStatement countStmt = conn.prepareStatement(createTableSql)) {
                countStmt.execute();
                conn.commit();
            } catch (Exception e) {
                log.error("自動(dòng)建表報(bào)錯(cuò)", e);
            } finally {
                //恢復(fù)狀態(tài)
                conn.setAutoCommit(preAutoCommitState);
                HANDLED_TABLE.addAll(prepareHandledTable);
            }
        }
    }

自動(dòng)建表邏輯說(shuō)明完之后,再回到剛剛的映射map的構(gòu)造上面,一種是通過(guò)本地線程的map

Map<String, String> routingTableMap = new HashMap<>(tableNames.size());
        if (TableShardHolder.hasVal()) {
            for (String tableName : tableNames) {
                if (TableShardHolder.containTable(tableName)) {
                    routingTableMap.put(tableName, TableShardHolder.getReplaceName(tableName));
                }
            }
        }

一種是通過(guò)參數(shù)+分表策略獲取替換后的表

首先通過(guò)mapper上面的注解獲取默認(rèn)的分表策略,然后查看方法參數(shù)有沒(méi)有,有的話就以方法參數(shù)為準(zhǔn),但是這里也要兼顧了常用的hash邏輯

Class<? extends ITableShardStrategy> shardStrategy = annotation.shardStrategy();
        boolean autoHash = false;
        if (annotation.hashTableLength() != -1) {
            shardStrategy = ITableShardStrategy.HashStrategy.class;
            if (TableShardHolder.hashTableLength() == null) {
                autoHash = true;
                TableShardHolder.hashTableLength(annotation.hashTableLength());
            }
        }
        ITableShardStrategy strategy = SHARD_STRATEGY.computeIfAbsent(shardStrategy, e -> (ITableShardStrategy) getObjectByClass(e));
        if (strategy == null) {
            return invocation.proceed();
        }
        Object objFromCurMethod = null;
        for (String tableName : tableNames) {
            String resName = null;
            if (objFromCurMethod == null) {
                Pair<Object, ITableShardStrategy> res = getObjFromCurMethod(curMethod.parameters, boundSql, autoHash);
                if (res.getRight() != null) {
                    strategy = res.getRight();
                }
                objFromCurMethod = res.getLeft();
            }
            resName = strategy.routingTable(tableName, objFromCurMethod);
            routingTableMap.put(tableName, resName);
        }

上面這段代碼主要獲取了實(shí)際的分表策略,和對(duì)應(yīng)的參數(shù),然后存入映射表里面,那么如何獲取實(shí)際的分表策略和參數(shù)呢,主要有以下兩個(gè)方法

通過(guò)boundSql對(duì)象獲取方法參數(shù)的實(shí)際值,然后遍歷獲取符合的參數(shù)值,如果入?yún)⑹强傻模湍玫谝粋€(gè)非可迭代的值作為分表策略的入?yún)?,所以要求同一批?shù)據(jù)中分表的策略都是一樣的,這里由于在攔截器不好做,所以放到了service層去處理

private Pair<Object, ITableShardStrategy> getObjFromCurMethod(Parameter[] parameters, BoundSql boundSql, boolean isAutoHash) {
        Object parameterObject = boundSql.getAdditionalParameter("_parameter");
        if (parameterObject == null) {
            parameterObject = boundSql.getParameterObject();
        }
        if (parameterObject == null || parameters.length == 0) {
            return null;
        }
        Parameter defaultParam = parameters[0];
        ITableShardStrategy res = null;
        for (int i = 0; i < parameters.length; i++) {
            Parameter cur = parameters[i];
            if (cur.isAnnotationPresent(TableShardParam.class)) {
                defaultParam = cur;
                TableShardParam annotation = cur.getAnnotation(TableShardParam.class);
                Class<? extends ITableShardStrategy> shardStrategy = annotation.shardStrategy();
                if (isAutoHash && annotation.enableHash()) {
                    //如果支持hash
                    shardStrategy = ITableShardStrategy.HashStrategy.class;
                    //如果當(dāng)前mapper為hash模式,并且對(duì)應(yīng)的長(zhǎng)度不為-1,設(shè)置長(zhǎng)度
                    if (annotation.hashTableLength() != -1) {
                        TableShardHolder.hashTableLength(annotation.hashTableLength());
                    }
                }
                res = SHARD_STRATEGY.computeIfAbsent(shardStrategy, e -> (ITableShardStrategy) getObjectByClass(e));
                break;
            }
        }
        Object paramValue = null;
        if (defaultParam.isAnnotationPresent(Param.class)) {
            String value = defaultParam.getAnnotation(Param.class).value();
            paramValue = ((MapperMethod.ParamMap) parameterObject).get(value);
        } else {
            paramValue = parameterObject;
        }
        return Pair.of(getInnerObj(paramValue), res);
    }
 
    private static Object getInnerObj(Object paramValue) {
        if (paramValue instanceof Iterable) {
            Iterable value = (Iterable) paramValue;
            Iterator iterator = value.iterator();
            while (iterator.hasNext()) {
                return getInnerObj(iterator.next());
            }
        }
        return paramValue;
    }

最后就是處理我們的sql,把生成的map進(jìn)行值替換

private void replaceSql(MetaObject metaObject, BoundSql boundSql, Map<String, String> routingTableMap) {
        String sql = boundSql.getSql();
        for (Map.Entry<String, String> entry : routingTableMap.entrySet()) {
            sql = sql.replaceAll(entry.getKey(), entry.getValue());
        }
        metaObject.setValue("delegate.boundSql.sql", sql);
    }

以上就是整套攔截器的實(shí)現(xiàn)代碼和思路

四、測(cè)試

具體代碼可以查看github項(xiàng)目的example模塊

測(cè)試代碼如下

@SpringBootApplication(scanBasePackages = "com.xl.mphelper.*")
@MapperScan(basePackages = "com.xl.mphelper.example.mapper")
@Slf4j
public class MpHelperApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(MpHelperApplication.class, args);
        OrderController controller = run.getBean(OrderController.class);
        List<OrderInfo> orderInfos = controller.testAdd();
        String suffix = orderInfos.get(0).suffix();
        Page<OrderInfo> orderInfoPage = controller.queryByPage(suffix);
        log.info("分頁(yè)查詢(xún){}", orderInfoPage.getRecords().size());
        List<OrderInfo> query = controller.query(suffix);
        log.info("查詢(xún)所有{}", query.size());
        IOrderService service = run.getBean(IOrderService.class);
        //自定義service的crud操作
        service.testCustomServiceShardCUD();
 
    }
}

測(cè)試結(jié)果如下

可以看到是先去數(shù)據(jù)庫(kù)查詢(xún)是否存在該表,沒(méi)有的話就進(jìn)行建表操作,分頁(yè)操作通過(guò)本地線程進(jìn)行了表名的替換

接下來(lái)是基于service分組的增刪改的案例

附上service層實(shí)現(xiàn)的方法,主要是根據(jù)接口進(jìn)行分組處理

 /**
     * 分表新增
     * @param entityList
     * @return
     */
    public boolean saveBatchShard(Collection<T> entityList) {
        if (CollectionUtils.isEmpty(entityList)) {
            return false;
        }
        T param = entityList.iterator().next();
        if (param instanceof Shardable) {
            Collection<Shardable> shardables = (Collection<Shardable>) entityList;
            shardables.stream().collect(Collectors.groupingBy(Shardable::suffix)).forEach((k, v) -> {
                TableShardHolder.putVal(param.getClass(),k);
                super.saveBatch((Collection<T>) v);
                TableShardHolder.remove(param.getClass());
            });
            return true;
        }
        return false;
    }
 
   public boolean updateBatchByShard(Collection<T> entityList){
       if (CollectionUtils.isEmpty(entityList)) {
           return false;
       }
       T param = entityList.iterator().next();
       if (param instanceof Shardable) {
           Collection<Shardable> shardables = (Collection<Shardable>) entityList;
           shardables.stream().collect(Collectors.groupingBy(Shardable::suffix)).forEach((k, v) -> {
               TableShardHolder.putVal(param.getClass(),k);
               super.updateBatchById((Collection<T>) v);
               TableShardHolder.remove(param.getClass());
           });
           return true;
       }
       return false;
   }
 
    /**
     * 分表刪除
     * @param entityList
     * @return
     */
    public boolean removeByShard(Collection<T> entityList){
        if (CollectionUtils.isEmpty(entityList)) {
            return false;
        }
        T param = entityList.iterator().next();
        if (param instanceof Shardable) {
            Collection<Shardable> shardables = (Collection<Shardable>) entityList;
            String keyProperty = getKeyPropertyFromLists(entityList);
            shardables.stream().collect(Collectors.groupingBy(Shardable::suffix)).forEach((k, v) -> {
                TableShardHolder.putVal(param.getClass(),k);
                List<Serializable> id=new ArrayList<>(v.size());;
                for (Shardable shardable : v) {
                    Serializable idValue = (Serializable) ReflectionKit.getFieldValue(shardable, keyProperty);
                    if(Objects.nonNull(idValue)){
                        id.add(idValue);
                    }
                }
                super.removeByIds(id);
                TableShardHolder.remove(param.getClass());
            });
            return true;
        }
        return false;
    }

為了簡(jiǎn)化操作,這里對(duì)hash,本地線程替換的方法抽取出來(lái)

public void wrapRunnable(Runnable runnable, Map<Class, String> map) {
        putValIfExistHashStrategy();
        for (Map.Entry<Class, String> entry : map.entrySet()) {
            TableShardHolder.putVal(entry.getKey(), entry.getValue());
        }
        runnable.run();
        for (Map.Entry<Class, String> entry : map.entrySet()) {
            TableShardHolder.remove(entry.getKey());
        }
        TableShardHolder.clearHashTableLength();
    }
 
 
  public void putValIfExistHashStrategy() {
        TableShard annotation = mapperClass.getAnnotation(TableShard.class);
        if (annotation == null) {
            throw new IllegalStateException("not found tableShard in mapper");
        }
        int i = annotation.hashTableLength();
        if (i != -1) {
            TableShardHolder.hashTableLength(i);
        }
    }

這里的查詢(xún)采用本地線程調(diào)用,也是通過(guò)包裝對(duì)通用的操作進(jìn)行屏蔽

 Page<OrderInfo> page = new Page<>();
        Page<OrderInfo> res = (Page<OrderInfo>) wrapSupplier(() -> orderInfoMapper.testLeftJoin(page, month), KVBuilder.init(OrderInfo.class, month).put(OrderDetail.class, month)
        );
        return res;

也可以直接通過(guò)mapper方法的參數(shù)進(jìn)行表路由的操作

關(guān)于hash有個(gè)額外注意點(diǎn)——如果mapper是hash策略,且本地線程沒(méi)有指定hash策略,而方法上面指定了param參數(shù)且沒(méi)有開(kāi)啟enableHash,就會(huì)走到默認(rèn)的分表策略

List<OrderInfo> testLeftJoin2(@TableShardParam String month);

然后是hash路由的測(cè)試,把對(duì)應(yīng)的注解注釋打開(kāi)

//@TableShard(enableCreateTable = true, createTableMethod = "createTable")
@TableShard(enableCreateTable = true,createTableMethod = "createTable", hashTableLength = 10)
public interface OrderDetailMapper extends CustomMapper<OrderDetail> {
    void createTable();
}
 
 
//@TableShard(enableCreateTable = true, createTableMethod = "createTable")
@TableShard(enableCreateTable = true, createTableMethod = "createTable", hashTableLength = 10)
public interface OrderInfoMapper extends CustomMapper<OrderInfo> {
    void createTable();
//注意,這里調(diào)用的service層沒(méi)設(shè)置本地線程變量,如果enableHash也為false,則不會(huì)調(diào)用hash策略
    List<OrderInfo> testLeftJoin2(@TableShardParam(enableHash = true)
                                          //@TableShardParam
                                          String month);
 
 
    Page<OrderInfo> testLeftJoin(IPage page, @TableShardParam String month);
 
    @TableShardIgnore
    @Select("select * from order_info where update_time is null")
    Cursor<OrderInfo> test();
}

測(cè)試結(jié)果

 

也可以看到對(duì)應(yīng)的數(shù)據(jù)庫(kù)表已經(jīng)建立起來(lái)

后記

以上是全部?jī)?nèi)容,在做的時(shí)候也參考了別人的一些做法,結(jié)合了自己的一些想法,最后形成本文,代碼已上傳的到GitHub, 有興趣的小伙伴可以下來(lái)看看,里面有一些關(guān)于sqlInject的用法,具體解析可以參考我另一篇博文,但這些還是有很多改進(jìn)的點(diǎn),主要是屬性寫(xiě)死在代碼里面,不是很靈活,比如把注解上面的屬性改為配置處理,以適配不同環(huán)境等

到此這篇關(guān)于springboot+mybatis-plus基于攔截器實(shí)現(xiàn)分表的文章就介紹到這了,更多相關(guān)springboot+mybatis-plus基于攔截器實(shí)現(xiàn)分表內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論