MyBatis分表插件(一)

分表插件

現有業務已經有現成的分表插件,整個是使用很古老的jade管理的一套工具,在項目準備切換到SpringBoot+MyBatis時,這種方式無法直接支持,所以基於SpringAop搞了個簡單的分表插件,目前屬於實驗性質,不過項目遷移的目的是達到了。


MyBatis分表插件(一)


原理

因為MyBatis本身代理了SQL處理,因此可以DAO層,執行SQL時,做改寫,設置路由,根據路由結果確定分表。 同時,也為了儘量兼容舊的代碼,減少修改,在DAO層的參數上添加一個同名的@ShardBy 註解,用來標記拆分鍵。 拆分策略則直接用現有的水平拆分,設置為拆分鍵取餘100,作為分表後綴。其中需要從SQL解析出表名稱,可以使用現有如h2,mycat等的SQL解析器。這裡使用了jade現有的一個SQL解析方法。

代碼

  1. 分表插件
<code>@Intercepts(@Signature(
type = StatementHandler.class,
method = "prepare",
args = {Connection.class, Integer.class}
))
@Component
public class ShardInterceptor implements Interceptor {
private static final ReflectorFactory defaultReflectorFactory = new DefaultReflectorFactory();

@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
MetaObject metaObject = MetaObject.forObject(statementHandler,
SystemMetaObject.DEFAULT_OBJECT_FACTORY,
SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,
defaultReflectorFactory
);
BoundSql boundSql = statementHandler.getBoundSql();
String sql = boundSql.getSql();

HashMap<string> parameterObject = (HashMap<string>) boundSql.getParameterObject();
MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");

String id = mappedStatement.getId();
String dao = id.substring(0, id.lastIndexOf("."));
String methodName = id.substring(id.lastIndexOf(".") + 1);
;
Class clazz = Class.forName(dao);

for (Method method : clazz.getMethods()) {
if (method.getName().equals(methodName)) {
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
int idx = 0;
for (Annotation[] pa : parameterAnnotations) {
for (Annotation a : pa) {
if (a instanceof ShardBy) {

Long value = (Long) parameterObject.get(method.getParameters()[idx].getName());
//jade 的表解析,可以用h2或mycat的替換
SQLParseInfo parseInfo = SQLParseInfo.getParseInfo(sql);
//單SQL多表的情況
if (parseInfo.getTables() == null || parseInfo.getTables().length != 1) {
throw new Throwable("不支持多個表");
}
String originTable = parseInfo.getTables()[0].getName();
String forwardTable = shard(originTable, value);
Field field = boundSql.getClass().getDeclaredField("sql");
field.setAccessible(true);
field.set(boundSql, sql.replace(originTable, forwardTable));
return invocation.proceed();
}
}
idx++;
}
}
}

return invocation.proceed();
}

//拆分策略
private String shard(String tableName, long value) {
return tableName + "_" + value % 100;
}
}

/<string>/<string>/<code>
  1. DAO層參數註解
<code>import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface ShardBy {

}

/<code>

使用舉例: UserTaskDao long selectUserTask(@ShardBy long userId, int bizType);

總結

以上的插件基本滿足了需求,但還有以下幾個點可以做進一步的優化。

  1. 解析多表的情況。這塊需要詳細處理下,業務中單SQL多表的情況還是很多的,引申包括對別名表的解析。其中複雜的是多表情況下的拆分邏輯。
  2. 可以看到SQL解析完成後,一個DAO對應的表名在啟動後是不會變的,所以可以用MAP做緩存,不用每次請求都去解析SQL。
  3. 目前包括策略都是寫在代碼裡的,都可以拆出來做成可配置,理想的情況是可以整合到一個SpringBoot Starter裡。
  4. 還有一點,可以考慮支持多策略的分表,除水平取餘外的hash分片等。
  5. 最後,目前對於事務都沒有考慮,單純拆表的話,這塊暫時不用過多考慮。


分享到:


相關文章: