资讯专栏INFORMATION COLUMN

mybatis利用插件实现分表

BDEEFE / 1964人阅读

摘要:如标题,这次的分表规则比较,部分用户相关表按产品维度划分,例如,是产品,新加一个产品就要新增一整套表研究了一波后面改成了不太合适,也有种杀鸡牛刀的感觉。

如标题,这次的分表规则比较??,部分用户相关表按产品维度划分,例如:user_1,user_2(1,2是产品id,新加一个产品就要新增一整套表...)研究了一波sharing-jdbc(后面改成了sharding-sphere)不太合适,也有种杀鸡牛刀的感觉。
不想手写SQL太麻烦,后面说不好表要改动,虽然有生成工具(不灵活),所以选择了Mybatis-plus这个兄弟,借鉴他的分页等各种插件决定自己实现一个分表插件,把需要分表的表在配置中维护,利用jsqlparser解析sql重写sql语句,废话不多说上代码

/**

分表插件

@author chonglou

@date 2019/2/2117:04

*/
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class ShardInterceptor implements Interceptor, ShardAgent {

private final ShardProperties shardProperties;

public ShardInterceptor(ShardProperties shardProperties) {
    this.shardProperties = shardProperties;
}

public static final CCJSqlParserManager parser = new CCJSqlParserManager();

@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = (StatementHandler) realTarget(invocation.getTarget());
    MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
    MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
    if (!shardProperties.isException(mappedStatement.getId())) {
        if (SqlCommandType.INSERT.equals(mappedStatement.getSqlCommandType())
                || SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())
                || SqlCommandType.UPDATE.equals(mappedStatement.getSqlCommandType())
                || SqlCommandType.DELETE.equals(mappedStatement.getSqlCommandType())) {

            String sql = statementHandler.getBoundSql().getSql();
            Statement statement = parser.parse(new StringReader(sql));
            if (statement instanceof Select) {
                Select select = (Select) statement;
                TableNameModifier modifier = new TableNameModifier(this);
                select.getSelectBody().accept(modifier);
            } else if (statement instanceof Update) {
                Update update = (Update) statement;
                List list = update.getTables();
                for (Table t : list) {
                    parserTable(t, true);
                }
            } else if (statement instanceof Delete) {
                Delete delete = (Delete) statement;
                parserTable(delete.getTable(), true);
                List
list = delete.getTables(); for (Table t : list) { parserTable(t, true); } } else if (statement instanceof Insert) { Insert insert = (Insert) statement; parserTable(insert.getTable(), false); } StatementDeParser deParser = new StatementDeParser(new StringBuilder()); statement.accept(deParser); sql = deParser.getBuffer().toString(); ReflectionUtils.setFieldValue(statementHandler.getBoundSql(), "sql", sql); } } return invocation.proceed(); } private Object realTarget(Object target) { if (Proxy.isProxyClass(target.getClass())) { MetaObject metaObject = SystemMetaObject.forObject(target); return realTarget(metaObject.getValue("h.target")); } else { return target; } } /** * 覆盖表名设置别名 * * @param table * @return */ private Table parserTable(Table table, boolean alias) { if (null != table) { if (alias) { table.setAlias(new Alias(table.getName())); } table.setName(getTargetTableName(table.getName())); } return table; } @Override public Object plugin(Object target) { if (target instanceof StatementHandler) { return Plugin.wrap(target, this); } return target; } @Override public void setProperties(Properties properties) { } @Override public String getTargetTableName(String tableName) { if (shardProperties.isAgentTable(tableName)) { return ShardUtil.getTargetTableName(tableName); } return tableName; }

}

/**

@author chonglou

@date 2019/2/2218:24

*/
public interface ShardAgent {

String getTargetTableName(String name);

}

/**
*工具

@author chonglou

@date 2019/2/2514:11

*/
public class ShardUtil {

private final static String KEY_GENERATOR = "keyGenerator";

public static void setKeyGenerator(Object keyGenerator) {
    HttpServletRequest request = SpringContextHolder.getRequest();
    request.setAttribute(KEY_GENERATOR, keyGenerator);
}

public static String getTargetTableName(String tableName) {
    HttpServletRequest request = SpringContextHolder.getRequest();
    Object productId = request.getAttribute(KEY_GENERATOR);
    if (null == productId) {
        throw new RuntimeException("keyGenerator is null.");
    }
    return tableName.concat("_").concat(productId.toString());
}

}

/**

Spring的ApplicationContext的持有者,可以用静态方法的方式获取spring容器中的bean,

Request 以及 Session

*

@author chonglou

*/
@Component
public class SpringContextHolder implements ApplicationContextAware {

private static ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    SpringContextHolder.applicationContext = applicationContext;
}

public static ApplicationContext getApplicationContext() {
    assertApplicationContext();
    return applicationContext;
}

public static  T getBean(String beanName) {
    assertApplicationContext();
    return (T) applicationContext.getBean(beanName);
}

public static  T getBean(Class requiredType) {
    assertApplicationContext();
    return applicationContext.getBean(requiredType);
}

private static void assertApplicationContext() {
    if (null == SpringContextHolder.applicationContext) {
        throw new RuntimeException("applicationContext属性为null,请检查是否注入了SpringContextHolder!");
    }
}

/**
 * 获取当前请求的Request对象
 *
 * @return HttpServletRequest
 */
public static HttpServletRequest getRequest() {
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    return requestAttributes.getRequest();
}

/**
 * 获取当前请求的session对象
 *
 * @return HttpSession
 */
public static HttpSession getSession() {
    return getRequest().getSession();
}

}

/**

查询语句修改

@author chonglou

@date 2019/2/2211:31

*/
public class TableNameModifier extends SelectDeParser {

private ShardAgent shardAgent;

TableNameModifier(ShardAgent shardAgent) {
    super();
    this.shardAgent = shardAgent;
}

@Override
public void visit(Table tableName) {
    StringBuilder buffer = new StringBuilder();
    tableName.setName(shardAgent.getTargetTableName(tableName.getName()));
    buffer.append(tableName.getFullyQualifiedName());
    Alias alias = tableName.getAlias();
    if (alias == null) {
        alias = new Alias(tableName.getName());
    }
    buffer.append(alias);
    Pivot pivot = tableName.getPivot();
    if (pivot != null) {
        pivot.accept(this);
    }

    MySQLIndexHint indexHint = tableName.getIndexHint();
    if (indexHint != null) {
        buffer.append(indexHint);
    }

}

}
/**

@author chonglou

@date 2019/2/2215:34

*/
@ConfigurationProperties(prefix = "shard.config")
public class ShardProperties {

private List exceptionMapperId;

private List agentTables;

public boolean isException(String mapperId) {
    return null != exceptionMapperId && exceptionMapperId.contains(mapperId);
}

public boolean isAgentTable(String tableName) {
    return null != agentTables && agentTables.contains(tableName);
}

public List getExceptionMapperId() {
    return exceptionMapperId;
}

public void setExceptionMapperId(List exceptionMapperId) {
    this.exceptionMapperId = exceptionMapperId;
}

public List getAgentTables() {
    return agentTables;
}

public void setAgentTables(List agentTables) {
    this.agentTables = agentTables;
}

}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77460.html

相关文章

  • 带你深入浅出MyBatis技术原理与实战(PDF实战实践)

    摘要:目录其中每个章节知识点都是相关连由浅入深的一步步全面分析了技术原理以及实战由于文案较长想深入学习以及对于该文档感兴趣的朋友们可以加群免费获取。这些场景在大量的编码中使用,具备较强的实用价值,这些内容都是通过实战得来的,供读者们参考。 前言系统掌握MyBatis编程技巧已经成了用Java构建移动互联网网站的必要条件 本文主要讲解了Mybatis的应用,解析了其原理,从而形成一个完整的知识...

    MoAir 评论0 收藏0
  • Sharding-Jdbc实现mysql分库分表

    摘要:实现数据库分库分表可以自己实现,也可以使用和实现。分布式数据库的自增不是自增的。分布式数据库分页查询需要使用插入时间实现。包含分库分片和读写分离功能。 Sharding-Jdbc实现mysql分库分表 简单介绍 数据库分库分表和读写分离区别,分库分表是在多个库建相同的表和同一个库建不同的表,根据随机或者哈希等方式查找实现。读写分离是为了解决数据库的读写性能不足,使用主库master进行...

    go4it 评论0 收藏0
  • Mybatis Interceptor 拦截器

    摘要:拦截器的使用场景主要是更新数据库的通用字段,分库分表,加解密等的处理。拦截器均需要实现该接口。拦截器拦截器的使用需要查看每一个所提供的方法参数。对应构造器,为,为,为。可参考拦截器原理探究。 拦截器(Interceptor)在 Mybatis 中被当做插件(plugin)对待,官方文档提供了 Executor(拦截执行器的方法),ParameterHandler(拦截参数的处理),Re...

    nemo 评论0 收藏0
  • springboot实践笔记之一:springboot+sharding-jdbc+mybatis

    摘要:现在的分片策略是上海深圳分别建库,每个库都存各自交易所的两支股票的,且按照月分表。五配置分片策略数据库分片策略在这个实例中,数据库的分库就是根据上海和深圳来分的,在中是单键分片。 由于当当发布了最新的Sharding-Sphere,所以本文已经过时,不日将推出新的版本 项目中遇到了分库分表的问题,找到了shrding-jdbc,于是就搞了一个springboot+sharding-jd...

    Snailclimb 评论0 收藏0
  • Spring Boot中整合Sharding-JDBC读写分离示例

    摘要:今天就给大家介绍下方式的使用,主要讲解读写分离的配置,其余的后面再介绍。主要还是用提供的,配置如下配置内容如下主数据源从数据源读写分离配置查询时的负载均衡算法,目前有种算法,轮询和随机,算法接口是。 在我《Spring Cloud微服务-全栈技术与案例解析》书中,第18章节分库分表解决方案里有对Sharding-JDBC的使用进行详细的讲解。 之前是通过XML方式来配置数据源,读写分离...

    kbyyd24 评论0 收藏0

发表评论

0条评论

BDEEFE

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<