如標題,此次的分表規則比較??,部分用戶相關表按產品維度劃分,例如:user_1,user_2(1,2是產品id,新加一個產品就要新增一整套表...)研究了一波sharing-jdbc(後面改爲了sharding-sphere)不太合適,也有種殺雞牛刀的感受。 不想手寫SQL太麻煩,後面說很差表要改動,雖然有生成工具(不靈活),因此選擇了Mybatis-plus這個兄弟,借鑑他的分頁等各類插件決定本身實現一個分表插件,把須要分表的表在配置中維護,利用jsqlparser解析sql重寫sql語句,廢話很少說上代碼
/**spring
*/
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class ShardInterceptor implements Interceptor, ShardAgent {sql
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<Table> list = update.getTables(); for (Table t : list) { parserTable(t, true); } } else if (statement instanceof Delete) { Delete delete = (Delete) statement; parserTable(delete.getTable(), true); List<Table> 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; }
}session
/**app
*/
public interface ShardAgent {ide
String getTargetTableName(String name);
}工具
/**
*工具ui
*/
public class ShardUtil {this
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()); }
}插件
/**code
*
*/
@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> T getBean(String beanName) { assertApplicationContext(); return (T) applicationContext.getBean(beanName); } public static <T> T getBean(Class<T> 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(); }
}
/**
*/
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); } }
}
/**
*/
@ConfigurationProperties(prefix = "shard.config")
public class ShardProperties {
private List<String> exceptionMapperId; private List<String> 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<String> getExceptionMapperId() { return exceptionMapperId; } public void setExceptionMapperId(List<String> exceptionMapperId) { this.exceptionMapperId = exceptionMapperId; } public List<String> getAgentTables() { return agentTables; } public void setAgentTables(List<String> agentTables) { this.agentTables = agentTables; }
}