您好,登錄后才能下訂單哦!
這篇文章主要講解了“springboot怎么配置sharding-jdbc水平分表”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“springboot怎么配置sharding-jdbc水平分表”吧!
官方給出了Spring Boot Starter配置
<dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId> <version>${shardingsphere.version}</version> </dependency>
但是基于已有項目,添加shardingsphere自動配置是很惡心的事
為什么配置了某個數據連接池的spring-boot-starter(比如druid)和 shardingsphere-jdbc-spring-boot-starter 時,系統啟動會報錯?
回答:
1. 因為數據連接池的starter(比如druid)可能會先加載并且其創建一個默認數據源,這將會使得 ShardingSphere‐JDBC 創建數據源時發生沖突。
2. 解決辦法為,去掉數據連接池的starter 即可,sharing‐jdbc 自己會創建數據連接池。
一般項目已經有自己的DataSource了,如果使用shardingsphere-jdbc的自動配置,就必須舍棄原有的DataSource。
為了不放棄原有的DataSource配置,我們只引入shardingsphere-jdbc-core依賴
<dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-core</artifactId> <version>4.1.1</version> </dependency>
如果只水平分表,只支持mysql,可以排除一些無用的依賴
<dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-core</artifactId> <version>4.1.1</version> <exclusions> <exclusion> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-sql-parser-postgresql</artifactId> </exclusion> <exclusion> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-sql-parser-oracle</artifactId> </exclusion> <exclusion> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-sql-parser-sqlserver</artifactId> </exclusion> <exclusion> <groupId>org.apache.shardingsphere</groupId> <artifactId>encrypt-core-rewrite</artifactId> </exclusion> <exclusion> <groupId>org.apache.shardingsphere</groupId> <artifactId>shadow-core-rewrite</artifactId> </exclusion> <exclusion> <groupId>org.apache.shardingsphere</groupId> <artifactId>encrypt-core-merge</artifactId> </exclusion> <exclusion> <!-- 數據庫連接池,一般原有項目已引入其他的連接池 --> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> </exclusion> <exclusion> <!-- 也是數據庫連接池,一般原有項目已引入其他的連接池 --> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> </exclusion> <exclusion> <!-- 對象池,可以不排除 --> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> </exclusion> <exclusion> <groupId>com.h3database</groupId> <artifactId>h3</artifactId> </exclusion> <exclusion> <!-- mysql驅動,原項目已引入,為了避免改變原有版本號,排除了吧 --> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </exclusion> <exclusion> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> </exclusion> <exclusion> <groupId>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</artifactId> </exclusion> </exclusions> </dependency>
以Druid為例,原配置為
package com.xxx.common.autoConfiguration; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.druid.filter.Filter; import com.alibaba.druid.filter.logging.Slf4jLogFilter; import com.alibaba.druid.filter.stat.StatFilter; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import com.alibaba.druid.wall.WallConfig; import com.alibaba.druid.wall.WallFilter; import lombok.extern.slf4j.Slf4j; /** * @ClassName: DruidConfiguration * @Description: Druid連接池配置 */ @Configuration @Slf4j public class DruidConfiguration { @Value("${spring.datasource.driver-class-name}") private String driver; @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Value("${datasource.druid.initialsize}") private Integer druid_initialsize = 0; @Value("${datasource.druid.maxactive}") private Integer druid_maxactive = 20; @Value("${datasource.druid.minidle}") private Integer druid_minidle = 0; @Value("${datasource.druid.maxwait}") private Integer druid_maxwait = 30000; @Bean public ServletRegistrationBean druidServlet() { ServletRegistrationBean reg = new ServletRegistrationBean(); reg.setServlet(new StatViewServlet()); reg.addUrlMappings("/druid/*"); reg.addInitParameter("loginUsername", "root"); reg.addInitParameter("loginPassword", "root!@#"); //reg.addInitParameter("logSlowSql", ""); return reg; } /** * * @Title: druidDataSource * @Description: 數據庫源Bean * @param @return 參數說明 * @return DataSource 返回類型 * @throws */ @Bean public DataSource druidDataSource() { // 數據源 DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(driver); // 驅動 druidDataSource.setUrl(url); // 數據庫連接地址 druidDataSource.setUsername(username); // 數據庫用戶名 druidDataSource.setPassword(password); // 數據庫密碼 druidDataSource.setInitialSize(druid_initialsize);// 初始化連接大小 druidDataSource.setMaxActive(druid_maxactive); // 連接池最大使用連接數量 druidDataSource.setMinIdle(druid_minidle); // 連接池最小空閑 druidDataSource.setMaxWait(druid_maxwait); // 獲取連接最大等待時間 // 打開PSCache,并且指定每個連接上PSCache的大小 druidDataSource.setPoolPreparedStatements(false); druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(33); //druidDataSource.setValidationQuery("SELECT 1"); // 用來檢測連接是否有效的sql druidDataSource.setTestOnBorrow(false); // 申請連接時執行validationQuery檢測連接是否有效,做了這個配置會降低性能。 druidDataSource.setTestOnReturn(false); // 歸還連接時執行validationQuery檢測連接是否有效,做了這個配置會降低性能 druidDataSource.setTestWhileIdle(false); // 建議配置為true,不影響性能,并且保證安全性。申請連接的時候檢測,如果空閑時間大于timeBetweenEvictionRunsMillis,執行validationQuery檢測連接是否有效 druidDataSource.setTimeBetweenLogStatsMillis(60000); // 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 druidDataSource.setMinEvictableIdleTimeMillis(1800000); // 配置一個連接在池中最小生存的時間,單位是毫秒 // 當程序存在缺陷時,申請的連接忘記關閉,這時候,就存在連接泄漏 // 配置removeAbandoned對性能會有一些影響,建議懷疑存在泄漏之后再打開。在上面的配置中,如果連接超過30分鐘未關閉,就會被強行回收,并且日志記錄連接申請時的調用堆棧。 druidDataSource.setRemoveAbandoned(false); // 打開removeAbandoned功能 druidDataSource.setRemoveAbandonedTimeout(1800); // 1800秒,也就是30分鐘 druidDataSource.setLogAbandoned(false); // 關閉abanded連接時輸出錯誤日志 // 過濾器 List<Filter> filters = new ArrayList<Filter>(); filters.add(this.getStatFilter()); // 監控 //filters.add(this.getSlf4jLogFilter()); // 日志 filters.add(this.getWallFilter()); // 防火墻 druidDataSource.setProxyFilters(filters); log.info("連接池配置信息:"+druidDataSource.getUrl()); return druidDataSource; } @Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); WebStatFilter webStatFilter = new WebStatFilter(); filterRegistrationBean.setFilter(webStatFilter); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; } /** * * @Title: getStatFilter * @Description: 監控過濾器 * @param @return 參數說明 * @return StatFilter 返回類型 * @throws */ public StatFilter getStatFilter(){ StatFilter sFilter = new StatFilter(); //sFilter.setSlowSqlMillis(2000); // 慢sql,毫秒時間 sFilter.setLogSlowSql(false); // 慢sql日志 sFilter.setMergeSql(true); // sql合并優化處理 return sFilter; } /** * * @Title: getSlf4jLogFilter * @Description: 監控日志過濾器 * @param @return 參數說明 * @return Slf4jLogFilter 返回類型 * @throws */ public Slf4jLogFilter getSlf4jLogFilter(){ Slf4jLogFilter slFilter = new Slf4jLogFilter(); slFilter.setResultSetLogEnabled(false); slFilter.setStatementExecutableSqlLogEnable(false); return slFilter; } /** * * @Title: getWallFilter * @Description: 防火墻過濾器 * @param @return 參數說明 * @return WallFilter 返回類型 * @throws */ public WallFilter getWallFilter(){ WallFilter wFilter = new WallFilter(); wFilter.setDbType("mysql"); wFilter.setConfig(this.getWallConfig()); wFilter.setLogViolation(true); // 對被認為是攻擊的SQL進行LOG.error輸出 wFilter.setThrowException(true); // 對被認為是攻擊的SQL拋出SQLExcepton return wFilter; } /** * * @Title: getWallConfig * @Description: 數據防火墻配置 * @param @return 參數說明 * @return WallConfig 返回類型 * @throws */ public WallConfig getWallConfig(){ WallConfig wConfig = new WallConfig(); wConfig.setDir("META-INF/druid/wall/mysql"); // 指定配置裝載的目錄 // 攔截配置-語句 wConfig.setTruncateAllow(false); // truncate語句是危險,缺省打開,若需要自行關閉 wConfig.setCreateTableAllow(true); // 是否允許創建表 wConfig.setAlterTableAllow(false); // 是否允許執行Alter Table語句 wConfig.setDropTableAllow(false); // 是否允許修改表 // 其他攔截配置 wConfig.setStrictSyntaxCheck(true); // 是否進行嚴格的語法檢測,Druid SQL Parser在某些場景不能覆蓋所有的SQL語法,出現解析SQL出錯,可以臨時把這個選項設置為false,同時把SQL反饋給Druid的開發者 wConfig.setConditionOpBitwseAllow(true); // 查詢條件中是否允許有"&"、"~"、"|"、"^"運算符。 wConfig.setMinusAllow(true); // 是否允許SELECT * FROM A MINUS SELECT * FROM B這樣的語句 wConfig.setIntersectAllow(true); // 是否允許SELECT * FROM A INTERSECT SELECT * FROM B這樣的語句 //wConfig.setMetadataAllow(false); // 是否允許調用Connection.getMetadata方法,這個方法調用會暴露數據庫的表信息 return wConfig; } }
可見,如果用自動配置的方式放棄這些原有的配置風險有多大
怎么改呢?
第一步,創建一個interface,用以加載自定義的分表策略
可以在各個子項目中創建bean,實現此接口
public interface ShardingRuleSupport { void configRule(ShardingRuleConfiguration shardingRuleConfig); }
第二步,在DruidConfiguration.class中注入所有的ShardingRuleSupport
@Autowired(required = false) private List<ShardingRuleSupport> shardingRuleSupport;
第三步,創建sharding-jdbc分表數據源
//包裝Druid數據源 Map<String, DataSource> dataSourceMap = new HashMap<>(); //自定義一個名稱為ds0的數據源名稱,包裝原有的Druid數據源,還可以再定義多個數據源 //因為只分表不分庫,所有定義一個數據源就夠了 dataSourceMap.put("ds0", druidDataSource); //加載分表配置 ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); //要加載所有的ShardingRuleSupport實現bean,所以用for循環加載 for (ShardingRuleSupport support : shardingRuleSupport) { support.configRule(shardingRuleConfig); } //加載其他配置 Properties properties = new Properties(); //由于未使用starter的自動裝配,所以手動設置,是否顯示分表sql properties.put("sql.show", sqlShow); //返回ShardingDataSource包裝的數據源 return ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfig, properties);
package com.xxx.common.autoConfiguration; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.druid.filter.Filter; import com.alibaba.druid.filter.logging.Slf4jLogFilter; import com.alibaba.druid.filter.stat.StatFilter; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import com.alibaba.druid.wall.WallConfig; import com.alibaba.druid.wall.WallFilter; import lombok.extern.slf4j.Slf4j; /** * @ClassName: DruidConfiguration * @Description: Druid連接池配置 */ @Configuration @Slf4j public class DruidConfiguration { @Value("${spring.datasource.driver-class-name}") private String driver; @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Value("${datasource.druid.initialsize}") private Integer druid_initialsize = 0; @Value("${datasource.druid.maxactive}") private Integer druid_maxactive = 20; @Value("${datasource.druid.minidle}") private Integer druid_minidle = 0; @Value("${datasource.druid.maxwait}") private Integer druid_maxwait = 30000; /** * 默認不顯示分表SQL */ @Value("${spring.shardingsphere.props.sql.show:false}") private boolean sqlShow; @Autowired(required = false) private List<ShardingRuleSupport> shardingRuleSupport; @Bean public ServletRegistrationBean druidServlet() { ServletRegistrationBean reg = new ServletRegistrationBean(); reg.setServlet(new StatViewServlet()); reg.addUrlMappings("/druid/*"); reg.addInitParameter("loginUsername", "root"); reg.addInitParameter("loginPassword", "root!@#"); //reg.addInitParameter("logSlowSql", ""); return reg; } /** * * @Title: druidDataSource * @Description: 數據庫源Bean * @param @return 參數說明 * @return DataSource 返回類型 * @throws */ @Bean public DataSource druidDataSource() { // 數據源 DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(driver); // 驅動 druidDataSource.setUrl(url); // 數據庫連接地址 druidDataSource.setUsername(username); // 數據庫用戶名 druidDataSource.setPassword(password); // 數據庫密碼 druidDataSource.setInitialSize(druid_initialsize);// 初始化連接大小 druidDataSource.setMaxActive(druid_maxactive); // 連接池最大使用連接數量 druidDataSource.setMinIdle(druid_minidle); // 連接池最小空閑 druidDataSource.setMaxWait(druid_maxwait); // 獲取連接最大等待時間 // 打開PSCache,并且指定每個連接上PSCache的大小 druidDataSource.setPoolPreparedStatements(false); druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(33); //druidDataSource.setValidationQuery("SELECT 1"); // 用來檢測連接是否有效的sql druidDataSource.setTestOnBorrow(false); // 申請連接時執行validationQuery檢測連接是否有效,做了這個配置會降低性能。 druidDataSource.setTestOnReturn(false); // 歸還連接時執行validationQuery檢測連接是否有效,做了這個配置會降低性能 druidDataSource.setTestWhileIdle(false); // 建議配置為true,不影響性能,并且保證安全性。申請連接的時候檢測,如果空閑時間大于timeBetweenEvictionRunsMillis,執行validationQuery檢測連接是否有效 druidDataSource.setTimeBetweenLogStatsMillis(60000); // 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 druidDataSource.setMinEvictableIdleTimeMillis(1800000); // 配置一個連接在池中最小生存的時間,單位是毫秒 // 當程序存在缺陷時,申請的連接忘記關閉,這時候,就存在連接泄漏 // 配置removeAbandoned對性能會有一些影響,建議懷疑存在泄漏之后再打開。在上面的配置中,如果連接超過30分鐘未關閉,就會被強行回收,并且日志記錄連接申請時的調用堆棧。 druidDataSource.setRemoveAbandoned(false); // 打開removeAbandoned功能 druidDataSource.setRemoveAbandonedTimeout(1800); // 1800秒,也就是30分鐘 druidDataSource.setLogAbandoned(false); // 關閉abanded連接時輸出錯誤日志 // 過濾器 List<Filter> filters = new ArrayList<Filter>(); filters.add(this.getStatFilter()); // 監控 //filters.add(this.getSlf4jLogFilter()); // 日志 filters.add(this.getWallFilter()); // 防火墻 druidDataSource.setProxyFilters(filters); log.info("連接池配置信息:"+druidDataSource.getUrl()); if (shardingRuleSupport == null || shardingRuleSupport.isEmpty()) { log.info("............分表配置為空,使用默認的數據源............"); return druidDataSource; } log.info("++++++++++++加載sharding jdbc配置++++++++++++"); //包裝Druid數據源 Map<String, DataSource> dataSourceMap = new HashMap<>(); //自定義一個名稱為ds0的數據源名稱,包裝原有的Druid數據源,還可以再定義多個數據源 //因為只分表不分庫,所有定義一個數據源就夠了 dataSourceMap.put("ds0", druidDataSource); //加載分表配置 ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); //要加載所有的ShardingRuleSupport實現bean,所以用for循環加載 for (ShardingRuleSupport support : shardingRuleSupport) { support.configRule(shardingRuleConfig); } //加載其他配置 Properties properties = new Properties(); //由于未使用starter的自動裝配,所以手動設置,是否顯示分表sql properties.put("sql.show", sqlShow); //返回ShardingDataSource包裝的數據源 return ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfig, properties); } @Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); WebStatFilter webStatFilter = new WebStatFilter(); filterRegistrationBean.setFilter(webStatFilter); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; } /** * * @Title: getStatFilter * @Description: 監控過濾器 * @param @return 參數說明 * @return StatFilter 返回類型 * @throws */ public StatFilter getStatFilter(){ StatFilter sFilter = new StatFilter(); //sFilter.setSlowSqlMillis(2000); // 慢sql,毫秒時間 sFilter.setLogSlowSql(false); // 慢sql日志 sFilter.setMergeSql(true); // sql合并優化處理 return sFilter; } /** * * @Title: getSlf4jLogFilter * @Description: 監控日志過濾器 * @param @return 參數說明 * @return Slf4jLogFilter 返回類型 * @throws */ public Slf4jLogFilter getSlf4jLogFilter(){ Slf4jLogFilter slFilter = new Slf4jLogFilter(); slFilter.setResultSetLogEnabled(false); slFilter.setStatementExecutableSqlLogEnable(false); return slFilter; } /** * * @Title: getWallFilter * @Description: 防火墻過濾器 * @param @return 參數說明 * @return WallFilter 返回類型 * @throws */ public WallFilter getWallFilter(){ WallFilter wFilter = new WallFilter(); wFilter.setDbType("mysql"); wFilter.setConfig(this.getWallConfig()); wFilter.setLogViolation(true); // 對被認為是攻擊的SQL進行LOG.error輸出 wFilter.setThrowException(true); // 對被認為是攻擊的SQL拋出SQLExcepton return wFilter; } /** * * @Title: getWallConfig * @Description: 數據防火墻配置 * @param @return 參數說明 * @return WallConfig 返回類型 * @throws */ public WallConfig getWallConfig(){ WallConfig wConfig = new WallConfig(); wConfig.setDir("META-INF/druid/wall/mysql"); // 指定配置裝載的目錄 // 攔截配置-語句 wConfig.setTruncateAllow(false); // truncate語句是危險,缺省打開,若需要自行關閉 wConfig.setCreateTableAllow(true); // 是否允許創建表 wConfig.setAlterTableAllow(false); // 是否允許執行Alter Table語句 wConfig.setDropTableAllow(false); // 是否允許修改表 // 其他攔截配置 wConfig.setStrictSyntaxCheck(true); // 是否進行嚴格的語法檢測,Druid SQL Parser在某些場景不能覆蓋所有的SQL語法,出現解析SQL出錯,可以臨時把這個選項設置為false,同時把SQL反饋給Druid的開發者 wConfig.setConditionOpBitwseAllow(true); // 查詢條件中是否允許有"&"、"~"、"|"、"^"運算符。 wConfig.setMinusAllow(true); // 是否允許SELECT * FROM A MINUS SELECT * FROM B這樣的語句 wConfig.setIntersectAllow(true); // 是否允許SELECT * FROM A INTERSECT SELECT * FROM B這樣的語句 //wConfig.setMetadataAllow(false); // 是否允許調用Connection.getMetadata方法,這個方法調用會暴露數據庫的表信息 return wConfig; } }
創建幾個ShardingRuleSupport接口的實現Bean
@Component public class DefaultShardingRuleAdapter implements ShardingRuleSupport { @Override public void configRule(ShardingRuleConfiguration shardingRuleConfiguration) { Collection<TableRuleConfiguration> tableRuleConfigs = shardingRuleConfiguration.getTableRuleConfigs(); TableRuleConfiguration ruleConfig1 = new TableRuleConfiguration("table_one", "ds0.table_one_$->{0..9}"); ComplexShardingStrategyConfiguration strategyConfig1 = new ComplexShardingStrategyConfiguration("column_id", new MyDefaultShardingAlgorithm()); ruleConfig1.setTableShardingStrategyConfig(strategyConfig1); tableRuleConfigs.add(ruleConfig1); TableRuleConfiguration ruleConfig2 = new TableRuleConfiguration("table_two", "ds0.table_two_$->{0..9}"); ComplexShardingStrategyConfiguration strategyConfig2 = new ComplexShardingStrategyConfiguration("column_id", new MyDefaultShardingAlgorithm()); ruleConfig2.setTableShardingStrategyConfig(strategyConfig2); tableRuleConfigs.add(ruleConfig2); } }
@Component public class CustomShardingRuleAdapter implements ShardingRuleSupport { @Override public void configRule(ShardingRuleConfiguration shardingRuleConfiguration) { Collection<TableRuleConfiguration> tableRuleConfigs = shardingRuleConfiguration.getTableRuleConfigs(); TableRuleConfiguration ruleConfig1 = new TableRuleConfiguration(MyCustomShardingUtil.LOGIC_TABLE_NAME, MyCustomShardingUtil.ACTUAL_DATA_NODES); ComplexShardingStrategyConfiguration strategyConfig1 = new ComplexShardingStrategyConfiguration(MyCustomShardingUtil.SHARDING_COLUMNS, new MyCustomShardingAlgorithm()); ruleConfig1.setTableShardingStrategyConfig(strategyConfig1); tableRuleConfigs.add(ruleConfig1); } }
public class MyDefaultShardingAlgorithm implements ComplexKeysShardingAlgorithm<String> { public String getShardingKey () { return "column_id"; } @Override public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<String> shardingValue) { Collection<String> col = new ArrayList<>(); String logicTableName = shardingValue.getLogicTableName() + "_"; Map<String, String> availableTargetNameMap = new HashMap<>(); for (String targetName : availableTargetNameMap) { String endStr = StringUtils.substringAfter(targetName, logicTableName); availableTargetNameMap.put(endStr, targetName); } int size = availableTargetNames.size(); //=,in Collection<String> shardingColumnValues = shardingValue.getColumnNameAndShardingValuesMap().get(this.getShardingKey()); if (shardingColumnValues != null) { for (String shardingColumnValue : shardingColumnValues) { String modStr = Integer.toString(Math.abs(shardingColumnValue .hashCode()) % size); String actualTableName = availableTargetNameMap.get(modStr); if (StringUtils.isNotEmpty(actualTableName)) { col.add(actualTableName); } } } //between and //shardingValue.getColumnNameAndRangeValuesMap().get(this.getShardingKey()); ... ... //如果分表列不是有序的,則between and無意義,沒有必要實現 return col; } }
public class MyCustomShardingAlgorithm extends MyDefaultShardingAlgorithm implements ComplexKeysShardingAlgorithm<String> { @Override public String getShardingKey () { return MyCustomShardingUtil.SHARDING_COLUMNS; } @Override public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<String> shardingValue) { Collection<String> col = new ArrayList<>(); String logicTableName = shardingValue.getLogicTableName() + "_"; Map<String, String> availableTargetNameMap = new HashMap<>(); for (String targetName : availableTargetNameMap) { String endStr = StringUtils.substringAfter(targetName, logicTableName); availableTargetNameMap.put(endStr, targetName); } Map<String, String> specialActualTableNameMap = MyCustomShardingUtil.getSpecialActualTableNameMap(); int count = (int) specialActualTableNameMap.values().stream().distinct().count(); int size = availableTargetNames.size() - count; //=,in Collection<String> shardingColumnValues = shardingValue.getColumnNameAndShardingValuesMap().get(this.getShardingKey()); if (shardingColumnValues != null) { for (String shardingColumnValue : shardingColumnValues) { String specialActualTableName = specialActualTableNameMap.get(shardingColumnValue); if (StringUtils.isNotEmpty(specialActualTableName)) { col.add(specialActualTableName); continue; } String modStr = Integer.toString(Math.abs(shardingColumnValue .hashCode()) % size); String actualTableName = availableTargetNameMap.get(modStr); if (StringUtils.isNotEmpty(actualTableName)) { col.add(actualTableName); } } } //between and //shardingValue.getColumnNameAndRangeValuesMap().get(this.getShardingKey()); ... ... //如果分表列不是有序的,則between and無意義,沒有必要實現 return col; } }
@Component public class MyCustomShardingUtil { /** * 邏輯表名 */ public static final String LOGIC_TABLE_NAME = "table_three"; /** * 分片字段 */ public static final String SHARDING_COLUMNS = "column_name"; /** * 添加指定分片表的后綴 */ private static final String[] SPECIAL_NODES = new String[]{"0sp", "1sp"}; // ds0.table_three_$->{((0..9).collect{t -> t.toString()} << ['0sp','1sp']).flatten()} public static final String ACTUAL_DATA_NODES = "ds0." + LOGIC_TABLE_NAME + "_$->{((0..9).collect{t -> t.toString()} << " + "['" + SPECIAL_NODES[0] + "','" + SPECIAL_NODES[1] + "']" + ").flatten()}"; private static final List<String> specialList0 = new ArrayList<>(); @Value("${special.table_three.sp0.ids:null}") private void setSpecialList0(String ids) { if (StringUtils.isBlank(ids)) { return; } String[] idSplit = StringUtils.split(ids, ","); for (String id : idSplit) { String trimId = StringUtils.trim(id); if (StringUtils.isEmpty(trimId)) { continue; } specialList0.add(trimId); } } private static final List<String> specialList1 = new ArrayList<>(); @Value("${special.table_three.sp1.ids:null}") private void setSpecialList1(String ids) { if (StringUtils.isBlank(ids)) { return; } String[] idSplit = StringUtils.split(ids, ","); for (String id : idSplit) { String trimId = StringUtils.trim(id); if (StringUtils.isEmpty(trimId)) { continue; } specialList1.add(trimId); } } private static class SpecialActualTableNameHolder { private static volatile Map<String, String> specialActualTableNameMap = new HashMap<>(); static { for (String specialId : specialList0) { specialActualTableNameMap.put(specialId, LOGIC_TABLE_NAME + "_" + SPECIAL_NODES[0]); } for (String specialId : specialList1) { specialActualTableNameMap.put(specialId, LOGIC_TABLE_NAME + "_" + SPECIAL_NODES[1]); } } } /** * @return 指定ID的表名映射 */ public static Map<String, String> getSpecialActualTableNameMap() { return SpecialActualTableNameHolder.specialActualTableNameMap; } }
ShardingAlgorithm接口的子接口除了ComplexKeysShardingAlgorithm,還有HintShardingAlgorithm,PreciseShardingAlgorithm,RangeShardingAlgorithm;本教程使用了更通用的ComplexKeysShardingAlgorithm接口。
配置TableRuleConfiguration類時,使用了兩個參數的構造器
public TableRuleConfiguration(String logicTable, String actualDataNodes) {}
TableRuleConfiguration類還有一個參數的的構造器,沒有實際數據節點,是給廣播表用的
public TableRuleConfiguration(String logicTable) {}
ds0.table_three_$->{((0…9).collect{t -> t.toString()} << [‘0sp',‘1sp']).flatten()}
sharding-jdbc的groovy行表達式支持$->{…}或${…},為了避免與spring的占位符混淆,官方推薦使用$->{…}
(0..9) 獲得0到9的集合
(0..9).collect{t -> t.toString()} 數值0到9的集合轉換成字符串0到9的數組
(0..9).collect{t -> t.toString()} << ['0sp','1sp'] 字符串0到9的數組合并['0sp','1sp']數組,結果為 ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ['0sp','1sp']]
flatten() 扁平化數組,結果為 ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0sp', '1sp']
#是否顯示分表SQL,默認為false spring.shardingsphere.props.sql.show=true #指定哪些列值入指定的分片表,多個列值以“,”分隔 #column_name為9997,9998,9999的記錄存入表table_three_0sp中 #column_name為1111,2222,3333,4444,5555的記錄存入表table_three_1sp中 #其余的值哈希取模后,存入對應的table_three_模數表中 special.table_three.sp0.ids=9997,9998,9999 special.table_three.sp1.ids=1111,2222,3333,4444,5555
任何SQL,只要select子句中包含動態參數,則拋出類型強轉異常
禁止修改分片鍵,如果update的set子句中存在分片鍵,則不能執行sql
感謝各位的閱讀,以上就是“springboot怎么配置sharding-jdbc水平分表”的內容了,經過本文的學習后,相信大家對springboot怎么配置sharding-jdbc水平分表這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。