所有原创©文章禁止任何形式转载,复用,修改转发,违者追究。
分表插件
现有业务已经有现成的分表插件,整个是使用很古老的jade管理的一套工具,在项目准备切换到SpringBoot+MyBatis时,这种方式无法直接支持,所以基于SpringAop搞了个简单的分表插件,目前属于实验性质,不过项目迁移的目的是达到了。
![aeb60d2ca6924223e3b4e0029b2dbca8.png](https://i-blog.csdnimg.cn/blog_migrate/dda45334e2e20d122dac228825c55edf.jpeg)
原理
因为MyBatis本身代理了SQL处理,因此可以DAO层,执行SQL时,做改写,设置路由,根据路由结果确定分表。 同时,也为了尽量兼容旧的代码,减少修改,在DAO层的参数上添加一个同名的@ShardBy 注解,用来标记拆分键。 拆分策略则直接用现有的水平拆分,设置为拆分键取余100,作为分表后缀。其中需要从SQL解析出表名称,可以使用现有如h2,mycat等的SQL解析器。这里使用了jade现有的一个SQL解析方法。
代码
- 分表插件
@Intercepts(@Signature( type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}))@Componentpublic 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 parameterObject = (HashMap) 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; }}
- DAO层参数注解
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 {}
使用举例: UserTaskDao long selectUserTask(@ShardBy long userId, int bizType);
总结
以上的插件基本满足了需求,但还有以下几个点可以做进一步的优化。
- 解析多表的情况。这块需要详细处理下,业务中单SQL多表的情况还是很多的,引申包括对别名表的解析。其中复杂的是多表情况下的拆分逻辑。
- 可以看到SQL解析完成后,一个DAO对应的表名在启动后是不会变的,所以可以用MAP做缓存,不用每次请求都去解析SQL。
- 目前包括策略都是写在代码里的,都可以拆出来做成可配置,理想的情况是可以整合到一个SpringBoot Starter里。
- 还有一点,可以考虑支持多策略的分表,除水平取余外的hash分片等。
- 最后,目前对于事务都没有考虑,单纯拆表的话,这块暂时不用过多考虑。