数据切分根据其切分类型,可以分为两种方式:垂直(纵向)切分和水平(横向)切分
ShardingSphere-Jdbc定位为轻量级Java框架,在Java的Jdbc层提供的额外服务。它使用客户端直连数据库,以jar包形式提供服务,可理解为增强版的Jdbc驱动,完全兼容Jdbc和各种ORM框架
docker配置mysql主从复制
1)创建主服务器所需目录
mkdir -p /usr/local/mysqlData/master/cnf mkdir -p /usr/local/mysqlData/master/data
2)定义主服务器配置文件
vim /usr/local/mysqlData/master/cnf/mysql.cnf
[mysqld] ## 设置server_id,注意要唯一 server-id=1 ## 开启binlog log-bin=mysql-bin ## binlog缓存 binlog_cache_size=1M ## binlog格式(mixed、statement、row,默认格式是statement) binlog_format=mixed
3)创建并启动mysql主服务
docker run -itd -p 3306:3306 --name master -v /usr/local/mysqlData/master/cnf:/etc/mysql/conf.d -v /usr/local/mysqlData/master/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 mysql:5.7
4)添加复制master数据的用户reader,供从服务器使用
[root@aliyun /]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 6af1df686fff mysql:5.7 "docker-entrypoint..." 5 seconds ago Up 4 seconds 0.0.0.0:3306->3306/tcp, 33060/tcp master [root@aliyun /]# docker exec -it master /bin/bash root@41d795785db1:/# mysql -u root -p123456 mysql> GRANT REPLICATION SLAVE ON *.* to 'reader'@'%' identified by 'reader'; Query OK, 0 rows affected, 1 warning (0.00 sec) mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec)
5)创建从服务器所需目录,编辑配置文件
mkdir /usr/local/mysqlData/slave/cnf -p vim /usr/local/mysqlData/slave/cnf/mysql.cnf
[mysqld] ## 设置server_id,注意要唯一 server-id=2 ## 开启binlog,以备Slave作为其它Slave的Master时使用 log-bin=mysql-slave-bin ## relay_log配置中继日志 relay_log=edu-mysql-relay-bin ## 如果需要同步函数或者存储过程 log_bin_trust_function_creators=true ## binlog缓存 binlog_cache_size=1M ## binlog格式(mixed、statement、row,默认格式是statement) binlog_format=mixed ## 跳过主从复制中遇到的所有错误或指定类型的错误,避免slave端复制中断 ## 如:1062错误是指一些主键重复,1032错误是因为主从数据库数据不一致 slave_skip_errors=1062
6)创建并运行mysql从服务器
docker run -itd -p 3307:3306 --name slaver -v /usr/local/mysqlData/slave/cnf:/etc/mysql/conf.d -v /usr/local/mysqlData/slave/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 mysql:5.7
7)在从服务器上配置连接主服务器的信息
首先主服务器上查看master_log_file、master_log_pos两个参数,然后切换到从服务器上进行主服务器的连接信息的设置
主服务上执行:
root@6af1df686fff:/# mysql -u root -p123456 mysql> show master status; +------------------+----------+--------------+------------------+-------------------+ | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set | +------------------+----------+--------------+------------------+-------------------+ | mysql-bin.000003 | 591 | | | | +------------------+----------+--------------+------------------+-------------------+ 1 row in set (0.00 sec)
docker查看主服务器容器的ip地址
[root@aliyun /]# docker inspect --format='{{.NetworkSettings.IPAddress}}' master 172.17.0.2
从服务器上执行:
[root@aliyun /]# docker exec -it slaver /bin/bash root@fe8b6fc2f1ca:/# mysql -u root -p123456 mysql> change master to master_host='172.17.0.2',master_user='reader',master_password='reader',master_log_file='mysql-bin.000003',master_log_pos=591;
8)从服务器启动I/O 线程和SQL线程
mysql> start slave; Query OK, 0 rows affected, 1 warning (0.00 sec) mysql> show slave status\G *************************** 1. row *************************** Slave_IO_State: Waiting for master to send event Master_Host: 172.17.0.2 Master_User: reader Master_Port: 3306 Connect_Retry: 60 Master_Log_File: mysql-bin.000003 Read_Master_Log_Pos: 591 Relay_Log_File: edu-mysql-relay-bin.000002 Relay_Log_Pos: 320 Relay_Master_Log_File: mysql-bin.000003 Slave_IO_Running: Yes Slave_SQL_Running: Yes
Slave_IO_Running: Yes,Slave_SQL_Running: Yes即表示启动成功。
4)两阶段提交
1)、新建Springboot工程,引入相关依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.21</version> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId> <version>4.0.0-RC1</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
2)、application.properties配置文件
spring.main.allow-bean-definition-overriding=true #显示sql spring.shardingsphere.props.sql.show=true #配置数据源 spring.shardingsphere.datasource.names=ds1,ds2,ds3 #master-ds1数据库连接信息 spring.shardingsphere.datasource.ds1.type=com.alibaba.druid.pool.DruidDataSource spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver spring.shardingsphere.datasource.ds1.url=jdbc:mysql://47.101.58.187:3306/sharding-jdbc-db?useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai spring.shardingsphere.datasource.ds1.username=root spring.shardingsphere.datasource.ds1.password=123456 spring.shardingsphere.datasource.ds1.maxPoolSize=100 spring.shardingsphere.datasource.ds1.minPoolSize=5 #slave-ds2数据库连接信息 spring.shardingsphere.datasource.ds2.type=com.alibaba.druid.pool.DruidDataSource spring.shardingsphere.datasource.ds2.driver-class-name=com.mysql.cj.jdbc.Driver spring.shardingsphere.datasource.ds2.url=jdbc:mysql://47.101.58.187:3307/sharding-jdbc-db?useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai spring.shardingsphere.datasource.ds2.username=root spring.shardingsphere.datasource.ds2.password=123456 spring.shardingsphere.datasource.ds2.maxPoolSize=100 spring.shardingsphere.datasource.ds2.minPoolSize=5 #slave-ds3数据库连接信息 spring.shardingsphere.datasource.ds3.type=com.alibaba.druid.pool.DruidDataSource spring.shardingsphere.datasource.ds3.driver-class-name=com.mysql.cj.jdbc.Driver spring.shardingsphere.datasource.ds3.url=jdbc:mysql://47.101.58.187:3307/sharding-jdbc-db?useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai spring.shardingsphere.datasource.ds3.username=root spring.shardingsphere.datasource.ds3.password=123456 spring.shardingsphere.datasource.ds.maxPoolSize=100 spring.shardingsphere.datasource.ds3.minPoolSize=5 #配置默认数据源ds1 默认数据源,主要用于写 spring.shardingsphere.sharding.default-data-source-name=ds1 #配置主从名称 spring.shardingsphere.masterslave.name=ms #置主库master,负责数据的写入 spring.shardingsphere.masterslave.master-data-source-name=ds1 #配置从库slave节点 spring.shardingsphere.masterslave.slave-data-source-names=ds2,ds3 #配置slave节点的负载均衡均衡策略,采用轮询机制 spring.shardingsphere.masterslave.load-balance-algorithm-type=round_robin #整合mybatis的配置 mybatis.type-aliases-package=com.ppdai.shardingjdbc.entity
3)、创建t_user表
CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nickname` varchar(100) DEFAULT NULL, `password` varchar(100) DEFAULT NULL, `sex` int(11) DEFAULT NULL, `birthday` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
4)、定义Controller、Mapper、Entity
@Data public class User { private Integer id; private String nickname; private String password; private Integer sex; private String birthday; }
@RestController @RequestMapping("/api/user") public class UserController { @Autowired private UserMapper userMapper; @PostMapping("/save") public String addUser() { User user = new User(); user.setNickname("zhangsan" + new Random().nextInt()); user.setPassword("123456"); user.setSex(1); user.setBirthday("1997-12-03"); userMapper.addUser(user); return "success"; } @GetMapping("/findUsers") public List<User> findUsers() { return userMapper.findUsers(); } }
public interface UserMapper { @Insert("insert into t_user(nickname,password,sex,birthday) values(#{nickname},#{password},#{sex},#{birthday})") void addUser(User user); @Select("select * from t_user") List<User> findUsers(); }
5)、验证
经校验写数据进入ds1数据库,而读操作则是ds2,ds3两个数据库轮询操作。
1)、分库分表
1)、逻辑表
用户数据根据订单id%2拆分为2个表,分别是:t_order0和t_order1。他们的逻辑表名是:t_order
多数据源相同表:
#多数据源$->{0..N}.逻辑表名$->{0..N} 相同表 spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds$->{0..1}.t_order$->{0..1}
多数据源不同表:
#多数据源$->{0..N}.逻辑表名$->{0..N} 不同表 spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds0.t_order$->{0..1},ds1.t_order$->{2..4}
单库分表:
#单数据源的配置方式 spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds0.t_order$->{0..4}
全部手动指定:
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds0.t_order0,ds1.t_order0,ds0.t_order1,ds1.t_order1
2)、inline分片策略
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds$->{0..1}.t_order$->{0..1} #数据源分片策略 spring.shardingsphere.sharding.tables.t_order.database-strategy.inline.sharding-column=user_id #数据源分片算法 spring.shardingsphere.sharding.tables.t_order.database-strategy.inline.algorithm-expression=ds$->{user_id%2} #表分片策略 spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.sharding-column=order_id #表分片算法 spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.algorithm-expression=t_order$->{order_id%2}
上面的配置通过user_id%2来决定具体数据源,通过order_id%2来决定具体表
insert into t_order(user_id,order_id) values(2,3),user_id%2 = 0使用数据源ds0,order_id%2 = 1使用t_order1,insert语句最终操作的是数据源ds0的t_order1表。
3)、分布式主键配置
Sharding-Jdbc可以配置分布式主键生成策略。默认使用雪花算法(snowflake),生成64bit的长整型数据,也支持UUID的方式
#主键的列名 spring.shardingsphere.sharding.tables.t_order.key-generator.column=id #主键生成策略 spring.shardingsphere.sharding.tables.t_order.key-generator.type=SNOWFLAKE
4)、inline分片策略实现分库分表
需求:
对1000w的用户数据进行分库分表,对用户表的数据进行分表和分库的操作。根据年龄奇数存储在t_user1,偶数t_user0,同时性别奇数存储在ds1,偶数ds0
表结构:
CREATE TABLE `t_user0` ( `id` bigint(20) DEFAULT NULL, `nickname` varchar(200) DEFAULT NULL, `password` varchar(200) DEFAULT NULL, `age` int(11) DEFAULT NULL, `sex` int(11) DEFAULT NULL, `birthday` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; CREATE TABLE `t_user1` ( `id` bigint(20) DEFAULT NULL, `nickname` varchar(200) DEFAULT NULL, `password` varchar(200) DEFAULT NULL, `age` int(11) DEFAULT NULL, `sex` int(11) DEFAULT NULL, `birthday` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
两个数据库中都包含t_user0和t_user1两张表
application.properties:
spring.main.allow-bean-definition-overriding=true #显示sql spring.shardingsphere.props.sql.show=true #配置数据源 spring.shardingsphere.datasource.names=ds0,ds1 #ds0数据库连接信息 spring.shardingsphere.datasource.ds0.type=com.alibaba.druid.pool.DruidDataSource spring.shardingsphere.datasource.ds0.driver-class-name=com.mysql.cj.jdbc.Driver spring.shardingsphere.datasource.ds0.url=jdbc:mysql://47.101.58.187:3306/t_user_db0?useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai spring.shardingsphere.datasource.ds0.username=root spring.shardingsphere.datasource.ds0.password=123456 spring.shardingsphere.datasource.ds0.maxPoolSize=100 spring.shardingsphere.datasource.ds0.minPoolSize=5 #ds1数据库连接信息 spring.shardingsphere.datasource.ds1.type=com.alibaba.druid.pool.DruidDataSource spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver spring.shardingsphere.datasource.ds1.url=jdbc:mysql://47.101.58.187:3306/t_user_db1?useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai spring.shardingsphere.datasource.ds1.username=root spring.shardingsphere.datasource.ds1.password=123456 spring.shardingsphere.datasource.ds1.maxPoolSize=100 spring.shardingsphere.datasource.ds1.minPoolSize=5 #整合mybatis的配置 mybatis.type-aliases-package=com.ppdai.shardingjdbc.entity spring.shardingsphere.sharding.tables.t_user.actual-data-nodes=ds$->{0..1}.t_user$->{0..1} #数据源分片策略 spring.shardingsphere.sharding.tables.t_user.database-strategy.inline.sharding-column=sex #数据源分片算法 spring.shardingsphere.sharding.tables.t_user.database-strategy.inline.algorithm-expression=ds$->{sex%2} #表分片策略 spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.sharding-column=age #表分片算法 spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.algorithm-expression=t_user$->{age%2} #主键的列名 spring.shardingsphere.sharding.tables.t_user.key-generator.column=id spring.shardingsphere.sharding.tables.t_user.key-generator.type=SNOWFLAKE
测试类:
@SpringBootTest class ShardingJdbcApplicationTests { @Autowired private UserMapper userMapper; /** * sex:奇数 * age:奇数 * ds1.t_user1 */ @Test public void test01() { User user = new User(); user.setNickname("zhangsan" + new Random().nextInt()); user.setPassword("123456"); user.setAge(17); user.setSex(1); user.setBirthday("1997-12-03"); userMapper.addUser(user); } /** * sex:奇数 * age:偶数 * ds1.t_user0 */ @Test public void test02() { User user = new User(); user.setNickname("zhangsan" + new Random().nextInt()); user.setPassword("123456"); user.setAge(18); user.setSex(1); user.setBirthday("1997-12-03"); userMapper.addUser(user); } /** * sex:偶数 * age:奇数 * ds0.t_user1 */ @Test public void test03() { User user = new User(); user.setNickname("zhangsan" + new Random().nextInt()); user.setPassword("123456"); user.setAge(17); user.setSex(2); user.setBirthday("1997-12-03"); userMapper.addUser(user); } /** * sex:偶数 * age:偶数 * ds0.t_user0 */ @Test public void test04() { User user = new User(); user.setNickname("zhangsan" + new Random().nextInt()); user.setPassword("123456"); user.setAge(18); user.setSex(2); user.setBirthday("1997-12-03"); userMapper.addUser(user); } }