当前位置:   article > 正文

Sharding Sphere分库分表-java配置_org.apache.shardingsphere.api.config.sharding.shar

org.apache.shardingsphere.api.config.sharding.shardingruleconfiguration设置s

注意:分库分表要注意id不能再用数据库自增方式。可以采用雪花算法(新增的表),自定义分片算法(旧表)

分片策略配置

对于分片策略存有数据源分片策略和表分片策略两种维度

  • 数据源分片策略:

    对应于DatabaseShardingStrategy。用于配置数据被分配的目标数据源

  • 表分片策略
    对应于TableShardingStrategy。用于配置数据被分配的目标表,该目标表存在与该数据的目标数据源内。故表分片策略是依赖与数据源分片策略的结果的

表:

  1. CREATE TABLE `t_user0` (
  2. `id` bigint(20) NOT NULL,
  3. `name` varchar(64) DEFAULT NULL COMMENT '名称',
  4. `city_id` int(12) DEFAULT NULL COMMENT '城市',
  5. `sex` tinyint(1) DEFAULT NULL COMMENT '性别',
  6. `phone` varchar(32) DEFAULT NULL COMMENT '电话',
  7. `email` varchar(32) DEFAULT NULL COMMENT '邮箱',
  8. `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  9. `password` varchar(32) DEFAULT NULL COMMENT '密码',
  10. PRIMARY KEY (`id`)
  11. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  12. CREATE TABLE `t_user1` (
  13. `id` bigint(20) NOT NULL,
  14. `name` varchar(64) DEFAULT NULL COMMENT '名称',
  15. `city_id` int(12) DEFAULT NULL COMMENT '城市',
  16. `sex` tinyint(1) DEFAULT NULL COMMENT '性别',
  17. `phone` varchar(32) DEFAULT NULL COMMENT '电话',
  18. `email` varchar(32) DEFAULT NULL COMMENT '邮箱',
  19. `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  20. `password` varchar(32) DEFAULT NULL COMMENT '密码',
  21. PRIMARY KEY (`id`)
  22. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

库:

   test0,test1

pom:

  1. <dependency>
  2. <groupId>org.apache.shardingsphere</groupId>
  3. <artifactId>sharding-jdbc-core</artifactId>
  4. <version>4.1.1</version>
  5. </dependency>

properties:

  1. spring.application.name=shardingjdbc
  2. server.port=8080
  3. datasource0.url=jdbc:mysql://localhost:3306/test0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
  4. datasource0.driver-class-name=com.mysql.cj.jdbc.Driver
  5. datasource0.type=com.alibaba.druid.pool.DruidDataSource
  6. datasource0.username=root
  7. datasource0.password=123456
  8. datasource1.url=jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
  9. datasource1.driver-class-name=com.mysql.cj.jdbc.Driver
  10. datasource1.type=com.alibaba.druid.pool.DruidDataSource
  11. datasource1.username=root
  12. datasource1.password=123456
  13. mybatis.mapper-locations=classpath:com/example/shardingjdbc/mapper/*.xml
  14. mybatis.type-aliases-package=com.example.shardingjdbc.**.entity
  15. #打印sql
  16. spring.shardingsphere.props.sql.show=true
  17. #
  18. spring.datasource.druid.filters=stat,wall,log4j2
  19. spring.datasource.druid.web-stat-filter.enabled=true
  20. spring.datasource.druid.web-stat-filter.url-pattern=/*
  21. spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
  22. spring.datasource.druid.web-stat-filter.session-stat-enable=true
  23. spring.datasource.druid.web-stat-filter.session-stat-max-count=1000
  24. #spring.datasource.druid.web-stat-filter.principal-session-name=
  25. #spring.datasource.druid.web-stat-filter.principal-cookie-name=
  26. #spring.datasource.druid.web-stat-filter.profile-enable=
  27. spring.datasource.druid.stat-view-servlet.enabled=true
  28. spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
  29. spring.datasource.druid.stat-view-servlet.reset-enable=false
  30. spring.datasource.druid.stat-view-servlet.login-username=admin
  31. spring.datasource.druid.stat-view-servlet.login-password=123
  32. spring.datasource.druid.stat-view-servlet.allow=127.0.0.1
  33. spring.datasource.druid.stat-view-servlet.deny=

 

主键策略:

  1. package com.example.shardingjdbc.config;
  2. import org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. @Configuration
  6. public class KeyIdConfig {
  7. @Bean("userKeyGenerator")
  8. public SnowflakeShardingKeyGenerator userKeyGenerator() {
  9. return new SnowflakeShardingKeyGenerator();
  10. }
  11. @Bean("orderKeyGenerator")
  12. public SnowflakeShardingKeyGenerator orderKeyGenerator() {
  13. return new SnowflakeShardingKeyGenerator();
  14. }
  15. }

 分表分库策略:

  1. package com.example.shardingjdbc.sharding;
  2. import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
  3. import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
  4. import java.util.Collection;
  5. public class UserShardingAlgorithm {
  6. public static final DatabaseShardingAlgorithm databaseShardingAlgorithm = new DatabaseShardingAlgorithm();
  7. public static final TableShardingAlgorithm tableShardingAlgorithm = new TableShardingAlgorithm();
  8. static class DatabaseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {
  9. @Override
  10. public String doSharding(Collection<String> databaseNames, PreciseShardingValue<Long> shardingValue) {
  11. for (String database : databaseNames) {
  12. if (database.endsWith(String.valueOf(shardingValue.getValue() % 2))) {
  13. return database;
  14. }
  15. }
  16. return "";
  17. }
  18. }
  19. static class TableShardingAlgorithm implements PreciseShardingAlgorithm<Long> {
  20. @Override
  21. public String doSharding(Collection<String> tableNames, PreciseShardingValue<Long> shardingValue) {
  22. for (String table : tableNames) {
  23. if (table.endsWith(String.valueOf(shardingValue.getValue() % 2))) {
  24. return table;
  25. }
  26. }
  27. return "";
  28. }
  29. }
  30. }

配置: 

1.分表不分库

 DataSourceConfig:

  1. package com.example.shardingjdbc.config;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import com.example.shardingjdbc.sharding.UserShardingAlgorithm;
  4. import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
  5. import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
  6. import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
  7. import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;
  8. import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
  9. import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
  10. import org.springframework.beans.factory.annotation.Value;
  11. import org.springframework.context.annotation.Bean;
  12. import org.springframework.context.annotation.Configuration;
  13. import javax.sql.DataSource;
  14. import java.util.HashMap;
  15. import java.util.Map;
  16. import java.util.Properties;
  17. @Configuration
  18. public class DataSourceConfig {
  19. @Value("${datasource0.url}")
  20. private String url0;
  21. @Value("${datasource0.username}")
  22. private String username0;
  23. @Value("${datasource0.password}")
  24. private String password0;
  25. @Value("${datasource0.driver-class-name}")
  26. private String driverClassName0;
  27. @Value(("${spring.datasource.druid.filters}"))
  28. private String filters;
  29. @Bean("dataSource")
  30. public DataSource dataSource() {
  31. try {
  32. DruidDataSource dataSource0 = new DruidDataSource();
  33. dataSource0.setDriverClassName(this.driverClassName0);
  34. dataSource0.setUrl(this.url0);
  35. dataSource0.setUsername(this.username0);
  36. dataSource0.setPassword(this.password0);
  37. dataSource0.setFilters(this.filters);
  38. //分库设置
  39. Map<String, DataSource> dataSourceMap = new HashMap<>(2);
  40. //添加数据库database0
  41. dataSourceMap.put("ds0", dataSource0);
  42. // 配置 t_user 表规则
  43. TableRuleConfiguration userRuleConfiguration = new TableRuleConfiguration("t_user", "ds0.t_user${0..1}");
  44. //此处可以自定义
  45. //userRuleConfiguration.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("id", "t_user${id % 2}"));
  46. StandardShardingStrategyConfiguration standardShardingStrategyConfiguration =
  47. new StandardShardingStrategyConfiguration("id", UserShardingAlgorithm.tableShardingAlgorithm);
  48. userRuleConfiguration.setTableShardingStrategyConfig(standardShardingStrategyConfiguration);
  49. //主键
  50. userRuleConfiguration.setKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLAKE", "id", getProperties()));
  51. // Sharding全局配置
  52. ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();
  53. shardingRuleConfiguration.getTableRuleConfigs().add(userRuleConfiguration);
  54. // 创建数据源
  55. DataSource dataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfiguration, new Properties());
  56. return dataSource;
  57. } catch (Exception ex) {
  58. ex.printStackTrace();
  59. return null;
  60. }
  61. }
  62. private static Properties getProperties() {
  63. Properties result = new Properties();
  64. result.setProperty("worker.id", "123");
  65. return result;
  66. }
  67. }

2.分库不分表

  1. package com.example.shardingjdbc.config;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import com.example.shardingjdbc.sharding.UserShardingAlgorithm;
  4. import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
  5. import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
  6. import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;
  7. import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
  8. import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
  9. import org.springframework.beans.factory.annotation.Value;
  10. import org.springframework.context.annotation.Bean;
  11. import org.springframework.context.annotation.Configuration;
  12. import javax.sql.DataSource;
  13. import java.util.*;
  14. @Configuration
  15. public class DataSourceConfig {
  16. @Value("${datasource0.url}")
  17. private String url0;
  18. @Value("${datasource0.username}")
  19. private String username0;
  20. @Value("${datasource0.password}")
  21. private String password0;
  22. @Value("${datasource0.driver-class-name}")
  23. private String driverClassName0;
  24. @Value("${datasource1.url}")
  25. private String url1;
  26. @Value("${datasource1.username}")
  27. private String username1;
  28. @Value("${datasource1.password}")
  29. private String password1;
  30. @Value("${datasource1.driver-class-name}")
  31. private String driverClassName1;
  32. @Value(("${spring.datasource.druid.filters}"))
  33. private String filters;
  34. @Bean("dataSource")
  35. public DataSource dataSource() {
  36. try {
  37. DruidDataSource dataSource0 = new DruidDataSource();
  38. dataSource0.setDriverClassName(this.driverClassName0);
  39. dataSource0.setUrl(this.url0);
  40. dataSource0.setUsername(this.username0);
  41. dataSource0.setPassword(this.password0);
  42. dataSource0.setFilters(this.filters);
  43. DruidDataSource dataSource1 = new DruidDataSource();
  44. dataSource1.setDriverClassName(this.driverClassName1);
  45. dataSource1.setUrl(this.url1);
  46. dataSource1.setUsername(this.username1);
  47. dataSource1.setPassword(this.password1);
  48. dataSource1.setFilters(this.filters);
  49. //分库设置
  50. Map<String, DataSource> dataSourceMap = new HashMap<>(2);
  51. //添加两个数据库database0和database1
  52. dataSourceMap.put("ds0", dataSource0);
  53. dataSourceMap.put("ds1", dataSource1);
  54. // 配置 t_user 表规则
  55. TableRuleConfiguration userRuleConfiguration = new TableRuleConfiguration("t_user", "ds${0..1}.t_user0");
  56. //id 是 偶数的都插入到了 test0 库的 t_user0 表中, 奇数的都插入到了 test1 库中的 t_user1 表中
  57. /**
  58. * #表策略 行表达式分表规则
  59. * sharding.jdbc.config.sharding.tables.user.actual-data-nodes=ds_$->{0..1}.user_$->{0..4}
  60. * sharding.jdbc.config.sharding.tables.user.table-strategy.inline.sharding-column=id
  61. * sharding.jdbc.config.sharding.tables.user.table-strategy.inline.algorithm-expression=user_$->{id % 5}
  62. * sharding.jdbc.config.sharding.tables.user.key-generator-column-name=id
  63. */
  64. // 行表达式分库规则
  65. /**
  66. * #库策略
  67. * sharding.jdbc.config.sharding.default-database-strategy.inline.sharding-column=id
  68. * harding.jdbc.config.sharding.default-database-strategy.inline.algorithm-expression=ds_$->{id % 2}
  69. */
  70. StandardShardingStrategyConfiguration standardShardingStrategyConfiguration =
  71. new StandardShardingStrategyConfiguration("id", UserShardingAlgorithm.databaseShardingAlgorithm);
  72. userRuleConfiguration.setDatabaseShardingStrategyConfig(standardShardingStrategyConfiguration);
  73. // Sharding全局配置
  74. ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();
  75. shardingRuleConfiguration.getTableRuleConfigs().add(userRuleConfiguration);
  76. // 创建数据源
  77. DataSource dataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfiguration, new Properties());
  78. return dataSource;
  79. } catch (Exception ex) {
  80. ex.printStackTrace();
  81. return null;
  82. }
  83. }
  84. }

3.分库分表

  1. package com.example.shardingjdbc.config;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import com.example.shardingjdbc.sharding.UserShardingAlgorithm;
  4. import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
  5. import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
  6. import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;
  7. import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
  8. import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
  9. import org.springframework.beans.factory.annotation.Value;
  10. import org.springframework.context.annotation.Bean;
  11. import org.springframework.context.annotation.Configuration;
  12. import javax.sql.DataSource;
  13. import java.util.*;
  14. @Configuration
  15. public class DataSourceConfig {
  16. @Value("${datasource0.url}")
  17. private String url0;
  18. @Value("${datasource0.username}")
  19. private String username0;
  20. @Value("${datasource0.password}")
  21. private String password0;
  22. @Value("${datasource0.driver-class-name}")
  23. private String driverClassName0;
  24. @Value("${datasource1.url}")
  25. private String url1;
  26. @Value("${datasource1.username}")
  27. private String username1;
  28. @Value("${datasource1.password}")
  29. private String password1;
  30. @Value("${datasource1.driver-class-name}")
  31. private String driverClassName1;
  32. @Value(("${spring.datasource.druid.filters}"))
  33. private String filters;
  34. @Bean("dataSource")
  35. public DataSource dataSource() {
  36. try {
  37. DruidDataSource dataSource0 = new DruidDataSource();
  38. dataSource0.setDriverClassName(this.driverClassName0);
  39. dataSource0.setUrl(this.url0);
  40. dataSource0.setUsername(this.username0);
  41. dataSource0.setPassword(this.password0);
  42. dataSource0.setFilters(this.filters);
  43. DruidDataSource dataSource1 = new DruidDataSource();
  44. dataSource1.setDriverClassName(this.driverClassName1);
  45. dataSource1.setUrl(this.url1);
  46. dataSource1.setUsername(this.username1);
  47. dataSource1.setPassword(this.password1);
  48. dataSource1.setFilters(this.filters);
  49. //分库设置
  50. Map<String, DataSource> dataSourceMap = new HashMap<>(2);
  51. //添加两个数据库database0和database1
  52. dataSourceMap.put("ds0", dataSource0);
  53. dataSourceMap.put("ds1", dataSource1);
  54. /**
  55. * 除了基本的分库分表规则以外,还有一些其他的配置,比如绑定表。这里先不一一举例了,参照官方文档配即可。
  56. *   举个例子:现在有 order, order_detail两张表,1:1的关系。
  57. *   在配置的时候,应该将相同 order_id 的 order 记录 和 order_detail 记录 映射到相同尾号的表中。这样方便连接查询。比如都插入到 order0, order_detail0中。
  58. *   如果配置了绑定关系,那么只会产生一条查询 select * from order0 as o join order_detail0 as d on o.order_id = d.order_id。
  59. *   否则会产生笛卡儿积查询,
  60. *     select * from order0 as o join order_detail0 as d on o.order_id = d.order_id。
  61. *     select * from order0 as o join order_detail1 as d on o.order_id = d.order_id。
  62. *     select * from order1 as o join order_detail0 as d on o.order_id = d.order_id。
  63. *     select * from order1 as o join order_detail1 as d on o.order_id = d.order_id。
  64. */
  65. // 配置 t_user 表规则 库:test0 test1 表 t_user1 t_user0
  66. TableRuleConfiguration userRuleConfiguration = new TableRuleConfiguration("t_user", "ds${0..1}.t_user${0..1}");
  67. //id 是 偶数的都插入到了 test0 库的 t_user0 表中, 奇数的都插入到了 test1 库中的 t_user1 表中
  68. /**
  69. * #表策略 行表达式分表规则
  70. * sharding.jdbc.config.sharding.tables.user.actual-data-nodes=ds_$->{0..1}.user_$->{0..1}
  71. * sharding.jdbc.config.sharding.tables.user.table-strategy.inline.sharding-column=id
  72. * sharding.jdbc.config.sharding.tables.user.table-strategy.inline.algorithm-expression=user_$->{id % 5}
  73. * sharding.jdbc.config.sharding.tables.user.key-generator-column-name=id
  74. */
  75. //sharding.jdbc.config.sharding.tables.user.table-strategy.standard.precise-algorithm-class-name: com.forezp.sharedingjdbcmasterslavetables.MyPreciseShardingAlgorithm
  76. //此处可以自定义
  77. userRuleConfiguration.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("id", "t_user${id % 2}"));
  78. // 行表达式分库规则
  79. /**
  80. * #库策略
  81. * sharding.jdbc.config.sharding.default-database-strategy.inline.sharding-column=id
  82. * harding.jdbc.config.sharding.default-database-strategy.inline.algorithm-expression=ds_$->{id % 2}
  83. */
  84. //根据城市分库
  85. userRuleConfiguration.setDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("city_id", "ds${city_id % 2}"));
  86. // Sharding全局配置
  87. ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();
  88. shardingRuleConfiguration.getTableRuleConfigs().add(userRuleConfiguration);
  89. // 创建数据源
  90. DataSource dataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfiguration, new Properties());
  91. return dataSource;
  92. } catch (Exception ex) {
  93. ex.printStackTrace();
  94. return null;
  95. }
  96. }
  97. }

注意:

  1.事务需要手动配置。

  2.手动开启sql打印

  3.跨节点连接查询问题(分页、排序)

  4.多数据源管理问题 

     分库分表根据业务划分:要注意各表之间的依赖关系,其有个体表,和全局表,全局表可以在每一个库中存放一份,以便提高查询的性能。如:用户表和用户地址表这两张表是相互依赖的,订单明细表和订单表也是相互依赖的,可以存访到一个库中中,减少网路请求I/O。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/756727
推荐阅读
相关标签
  

闽ICP备14008679号