声明
引用上文继续优化分库分表,上部分是单库分表
分库分表在原基础改动,变动不多
点我:java springboot mysql shardingsphere 分库分表 上 (单库分表)
yaml配置文件变动
server: port: 7070 spring: application: name: shadingsphere-name main: # 一个实体类对应两张表,覆盖 否则会报错 allow-bean-definition-overriding: true shardingsphere: #配置数据源 datasource: names: m1,m2 m1: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/sharding0?serverTimezone=GMT%2B8 username: root password: wuzhenyong1207 m2: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/sharding1?serverTimezone=GMT%2B8 username: root password: wuzhenyong1207 sharding: # 默认数据库策略 #default-database-strategy: # inline: # sharding-column: empno # algorithm-expression: m$->{empno % 2 } tables: # 表名 emp: # 配置表在哪个数据库里面 m1.emp0 ,m1.emp1 actual-data-nodes: m$->{1..2}.emp$->{0..1} # 生成ID key-generator: column: id # 自定义主键生成类型 官网有两种:UUID, SNOWFLAKE 雪花算法 type: SIMPLE # 指定表分片策略 table-strategy: inline: sharding-column: id algorithm-expression: emp$->{id % 2 } # 指定表 数据库分片策略 database-strategy: inline: sharding-column: empno algorithm-expression: m$->{empno % 2 + 1} props: # 开启sql日志 sql: show: true
小说明:指定表 数据库分片策略的字段尽量不要和表的策略字段是一样的,否则插入的表不会分散开
控制层方法更改
empno字段使用随即生成数 生成0或1
@GetMapping("/save") public String save() { int last = 50; for (int i = 0; i < 20; i++) { String value = String.valueOf(i); EmpEntity entity = new EmpEntity(); entity.setEmpno(getRandomNum()); entity.setEmpname(value); entity.setJob(value); entity.setMgr(value); entity.setHiredate(LocalDateTime.now()); entity.setSal(new BigDecimal(value)); entity.setComn(new BigDecimal(value)); entity.setDepno(value); empMapper.insert(entity); } return "添加成功"; } /** * 生成 0 或 1两个数 * @return */ private int getRandomNum(){ return (int) (Math.random() * 2); }