赞
踩
今天我们来聊一聊ShardingSphere,相信做过电商相关项目的同学应该都知道或者用过这个中间件,没错,它是一个用来解决在业务数据超过单表或单库最大接受性能的情景下而出现的一款产品,主要用来对业务数据做水平和横向的扩展,也就是我们常说的分库分表。
ShardingSphere是一套开源的分布式数据库中间件解决方案组成的生态圈,它由Sharding-JDBC、Sharding-Proxy和Sharding-Sidecar(计划中)这3款相互独立的产品组成。 他们均提供标准化的数据分片、分布式事务和数据库治理功能,可适用于如Java同构、异构语言、云原生等各种多样化的应用场景。
Sharding-JDBC
定位为轻量级Java框架,在Java的JDBC层提供的额外服务。 它使用客户端直连数据库,以jar包形式提供服务,无需额外部署和依赖,可理解为增强版的JDBC驱动,完全兼容JDBC和各种ORM框架。
Sharding-Proxy
定位为透明化的数据库代理端,提供封装了数据库二进制协议的服务端版本,用于完成对异构语言的支持。 目前先提供MySQL/PostgreSQL版本,它可以使用任何兼容MySQL/PostgreSQL协议的访问客户端(如:MySQL Command Client, MySQL Workbench, Navicat等)操作数据,对DBA更加友好。
Sharding-Sidecar(TODO)
定位为Kubernetes的云原生数据库代理,以Sidecar的形式代理所有对数据库的访问。 通过无中心、零侵入的方案提供与数据库交互的的啮合层,即Database Mesh,又可称数据网格。
Database Mesh的关注重点在于如何将分布式的数据访问应用与数据库有机串联起来,它更加关注的是交互,是将杂乱无章的应用与数据库之间的交互有效的梳理。使用Database Mesh,访问数据库的应用和数据库终将形成一个巨大的网格体系,应用和数据库只需在网格体系中对号入座即可,它们都是被啮合层所治理的对象。
数据分片
分布式事务
数据库治理
- <dependency>
- <groupId>org.apache.shardingsphere</groupId>
- <artifactId>sharding-jdbc-core</artifactId>
- <version>${sharding-sphere.version}</version>
- </dependency>
Sharding-JDBC的分库分表通过规则配置描述,以下例子是根据user_id取模分库, 且根据order_id取模分表的两库两表的配置。
- // 配置真实数据源
- Map<String, DataSource> dataSourceMap = new HashMap<>();
-
- // 配置第一个数据源
- BasicDataSource dataSource1 = new BasicDataSource();
- dataSource1.setDriverClassName("com.mysql.jdbc.Driver");
- dataSource1.setUrl("jdbc:mysql://localhost:3306/ds0");
- dataSource1.setUsername("root");
- dataSource1.setPassword("");
- dataSourceMap.put("ds0", dataSource1);
-
- // 配置第二个数据源
- BasicDataSource dataSource2 = new BasicDataSource();
- dataSource2.setDriverClassName("com.mysql.jdbc.Driver");
- dataSource2.setUrl("jdbc:mysql://localhost:3306/ds1");
- dataSource2.setUsername("root");
- dataSource2.setPassword("");
- dataSourceMap.put("ds1", dataSource2);
-
- // 配置Order表规则
- TableRuleConfiguration orderTableRuleConfig = new TableRuleConfiguration("t_order","ds${0..1}.t_order${0..1}");
-
- // 配置分库 + 分表策略
- orderTableRuleConfig.setDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_id", "ds${user_id % 2}"));
- orderTableRuleConfig.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("order_id", "t_order${order_id % 2}"));
-
- // 配置分片规则
- ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
- shardingRuleConfig.getTableRuleConfigs().add(orderTableRuleConfig);
-
- // 省略配置order_item表规则...
- // ...
-
- // 获取数据源对象
- DataSource dataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfig, new Properties());
基于Yaml的规则配置
- dataSources:
- ds0: !!org.apache.commons.dbcp.BasicDataSource
- driverClassName: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/ds0
- username: root
- password:
- ds1: !!org.apache.commons.dbcp.BasicDataSource
- driverClassName: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/ds1
- username: root
- password:
-
- shardingRule:
- tables:
- t_order:
- actualDataNodes: ds${0..1}.t_order${0..1}
- databaseStrategy:
- inline:
- shardingColumn: user_id
- algorithmExpression: ds${user_id % 2}
- tableStrategy:
- inline:
- shardingColumn: order_id
- algorithmExpression: t_order${order_id % 2}
- t_order_item:
- actualDataNodes: ds${0..1}.t_order_item${0..1}
- databaseStrategy:
- inline:
- shardingColumn: user_id
- algorithmExpression: ds${user_id % 2}
- tableStrategy:
- inline:
- shardingColumn: order_id
- algorithmExpression: t_order_item${order_id % 2}
DataSource dataSource = YamlShardingDataSourceFactory.createDataSource(yamlFile);
通过ShardingDataSourceFactory或者YamlShardingDataSourceFactory工厂和规则配置对象获取ShardingDataSource,ShardingDataSource实现自JDBC的标准接口DataSource。然后可通过DataSource选择使用原生JDBC开发,或者使用JPA, MyBatis等ORM工具。 以JDBC原生实现为例:
- DataSource dataSource = YamlShardingDataSourceFactory.createDataSource(yamlFile);
- String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id WHERE o.user_id=? AND o.order_id=?";
- try (
- Connection conn = dataSource.getConnection();
- PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
- preparedStatement.setInt(1, 10);
- preparedStatement.setInt(2, 1001);
- try (ResultSet rs = preparedStatement.executeQuery()) {
- while(rs.next()) {
- System.out.println(rs.getInt(1));
- System.out.println(rs.getInt(2));
- }
- }
- }
- <!-- for spring boot -->
- <dependency>
- <groupId>org.apache.shardingsphere</groupId>
- <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
- <version>${sharding-sphere.version}</version>
- </dependency>
-
- <!-- for spring namespace -->
- <dependency>
- <groupId>org.apache.shardingsphere</groupId>
- <artifactId>sharding-jdbc-spring-namespace</artifactId>
- <version>${sharding-sphere.version}</version>
- </dependency>
- spring.shardingsphere.datasource.names=ds0,ds1
-
- spring.shardingsphere.datasource.ds0.type=org.apache.commons.dbcp2.BasicDataSource
- spring.shardingsphere.datasource.ds0.driver-class-name=com.mysql.jdbc.Driver
- spring.shardingsphere.datasource.ds0.url=jdbc:mysql://localhost:3306/ds0
- spring.shardingsphere.datasource.ds0.username=root
- spring.shardingsphere.datasource.ds0.password=
-
- spring.shardingsphere.datasource.ds1.type=org.apache.commons.dbcp2.BasicDataSource
- spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.jdbc.Driver
- spring.shardingsphere.datasource.ds1.url=jdbc:mysql://localhost:3306/ds1
- spring.shardingsphere.datasource.ds1.username=root
- spring.shardingsphere.datasource.ds1.password=
-
- spring.shardingsphere.sharding.default-database-strategy.inline.sharding-column=user_id
- spring.shardingsphere.sharding.default-database-strategy.inline.algorithm-expression=ds$->{user_id % 2}
-
- spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds$->{0..1}.t_order$->{0..1}
- 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}
-
- spring.shardingsphere.sharding.tables.t_order_item.actual-data-nodes=ds$->{0..1}.t_order_item$->{0..1}
- spring.shardingsphere.sharding.tables.t_order_item.table-strategy.inline.sharding-column=order_id
- spring.shardingsphere.sharding.tables.t_order_item.table-strategy.inline.algorithm-expression=t_order_item$->{order_id % 2}
- <dependency>
- <groupId>org.apache.shardingsphere</groupId>
- <artifactId>sharding-jdbc-core</artifactId>
- <version>${sharding-sphere.version}</version>
- </dependency>
- // 配置真实数据源
- Map<String, DataSource> dataSourceMap = new HashMap<>();
-
- // 配置主库
- BasicDataSource masterDataSource = new BasicDataSource();
- masterDataSource.setDriverClassName("com.mysql.jdbc.Driver");
- masterDataSource.setUrl("jdbc:mysql://localhost:3306/ds_master");
- masterDataSource.setUsername("root");
- masterDataSource.setPassword("");
- dataSourceMap.put("ds_master", masterDataSource);
-
- // 配置第一个从库
- BasicDataSource slaveDataSource1 = new BasicDataSource();
- slaveDataSource1.setDriverClassName("com.mysql.jdbc.Driver");
- slaveDataSource1.setUrl("jdbc:mysql://localhost:3306/ds_slave0");
- slaveDataSource1.setUsername("root");
- slaveDataSource1.setPassword("");
- dataSourceMap.put("ds_slave0", slaveDataSource1);
-
- // 配置第二个从库
- BasicDataSource slaveDataSource2 = new BasicDataSource();
- slaveDataSource2.setDriverClassName("com.mysql.jdbc.Driver");
- slaveDataSource2.setUrl("jdbc:mysql://localhost:3306/ds_slave1");
- slaveDataSource2.setUsername("root");
- slaveDataSource2.setPassword("");
- dataSourceMap.put("ds_slave1", slaveDataSource2);
-
- // 配置读写分离规则
- MasterSlaveRuleConfiguration masterSlaveRuleConfig = new MasterSlaveRuleConfiguration("ds_master_slave", "ds_master", Arrays.asList("ds_slave0", "ds_slave1"));
-
- // 获取数据源对象
- DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap, masterSlaveRuleConfig, new Properties());
或通过Yaml方式配置,与以上配置等价:
- dataSources:
- ds_master: !!org.apache.commons.dbcp.BasicDataSource
- driverClassName: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/ds_master
- username: root
- password:
- ds_slave0: !!org.apache.commons.dbcp.BasicDataSource
- driverClassName: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/ds_slave0
- username: root
- password:
- ds_slave1: !!org.apache.commons.dbcp.BasicDataSource
- driverClassName: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/ds_slave1
- username: root
- password:
-
- masterSlaveRule:
- name: ds_ms
- masterDataSourceName: ds_master
- slaveDataSourceNames: [ds_slave0, ds_slave1]
-
- props:
- sql.show: true
DataSource dataSource = YamlMasterSlaveDataSourceFactory.createDataSource(yamlFile);
通过YamlMasterSlaveDataSourceFactory工厂和规则配置对象获取MasterSlaveDataSource,MasterSlaveDataSource实现自JDBC的标准接口DataSource。然后可通过DataSource选择使用原生JDBC开发,或者使用JPA, MyBatis等ORM工具。 以JDBC原生实现为例:
- DataSource dataSource = YamlMasterSlaveDataSourceFactory.createDataSource(yamlFile);
- String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id WHERE o.user_id=? AND o.order_id=?";
- try (
- Connection conn = dataSource.getConnection();
- PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
- preparedStatement.setInt(1, 10);
- preparedStatement.setInt(2, 1001);
- try (ResultSet rs = preparedStatement.executeQuery()) {
- while(rs.next()) {
- System.out.println(rs.getInt(1));
- System.out.println(rs.getInt(2));
- }
- }
- }
- <!-- for spring boot -->
- <dependency>
- <groupId>org.apache.shardingsphere</groupId>
- <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
- <version>${sharding-sphere.version}</version>
- </dependency>
- spring.shardingsphere.datasource.names=master,slave0,slave1
-
- spring.shardingsphere.datasource.master.type=org.apache.commons.dbcp.BasicDataSource
- spring.shardingsphere.datasource.master.driver-class-name=com.mysql.jdbc.Driver
- spring.shardingsphere.datasource.master.url=jdbc:mysql://localhost:3306/master
- spring.shardingsphere.datasource.master.username=root
- spring.shardingsphere.datasource.master.password=
-
- spring.shardingsphere.datasource.slave0.type=org.apache.commons.dbcp.BasicDataSource
- spring.shardingsphere.datasource.slave0.driver-class-name=com.mysql.jdbc.Driver
- spring.shardingsphere.datasource.slave0.url=jdbc:mysql://localhost:3306/slave0
- spring.shardingsphere.datasource.slave0.username=root
- spring.shardingsphere.datasource.slave0.password=
-
- spring.shardingsphere.datasource.slave1.type=org.apache.commons.dbcp.BasicDataSource
- spring.shardingsphere.datasource.slave1.driver-class-name=com.mysql.jdbc.Driver
- spring.shardingsphere.datasource.slave1.url=jdbc:mysql://localhost:3306/slave1
- spring.shardingsphere.datasource.slave1.username=root
- spring.shardingsphere.datasource.slave1.password=
-
- spring.shardingsphere.masterslave.name=ms
- spring.shardingsphere.masterslave.master-data-source-name=master
- spring.shardingsphere.masterslave.slave-data-source-names=slave0,slave1
-
- spring.shardingsphere.props.sql.show=true
如果您计划使用Spring boot + JNDI
的方式,在应用容器(如Tomcat)中使用Sharding-JDBC时,可使用spring.shardingsphere.datasource.${datasourceName}.jndiName
来代替数据源的一系列配置。 如
- spring.shardingsphere.datasource.names=master,slave0,slave1
-
- spring.shardingsphere.datasource.master.jndi-name=java:comp/env/jdbc/master
- spring.shardingsphere.datasource.slave0.jndi-name=jdbc/slave0
- spring.shardingsphere.datasource.slave1.jndi-name=jdbc/slave1
-
- spring.shardingsphere.masterslave.name=ms
- spring.shardingsphere.masterslave.master-data-source-name=master
- spring.shardingsphere.masterslave.slave-data-source-names=slave0,slave1
-
- spring.shardingsphere.props.sql.show=true
- <dependency>
- <groupId>org.apache.shardingsphere</groupId>
- <artifactId>sharding-jdbc-core</artifactId>
- <version>${sharding-sphere.version}</version>
- </dependency>
-
- <!-- 使用XA事务时,需要引入此模块 -->
- <dependency>
- <groupId>org.apache.shardingsphere</groupId>
- <artifactId>sharding-transaction-xa-core</artifactId>
- <version>${shardingsphere.version}</version>
- </dependency>
-
- <!-- 使用BASE事务时,需要引入此模块 -->
- <dependency>
- <groupId>org.apache.shardingsphere</groupId>
- <artifactId>sharding-transaction-base-seata-at</artifactId>
- <version>${sharding-sphere.version}</version>
- </dependency>
- TransactionTypeHolder.set(TransactionType.XA); // 支持TransactionType.LOCAL, TransactionType.XA, TransactionType.BASE
- try (Connection connection = dataSource.getConnection()) { // dataSource的类型为ShardingDataSource
- connection.setAutoCommit(false);
- PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO t_order (user_id, status) VALUES (?, ?)");
- preparedStatement.setObject(1, i);
- preparedStatement.setObject(2, "init");
- preparedStatement.executeUpdate();
- connection.commit();
- }
- <dependency>
- <groupId>org.apache.shardingsphere</groupId>
- <artifactId>sharding-jdbc-spring-namespace</artifactId>
- <version>${shardingsphere.version}</version>
- </dependency>
-
- <!-- 使用XA事务时,需要引入此模块 -->
- <dependency>
- <groupId>org.apache.shardingsphere</groupId>
- <artifactId>sharding-transaction-xa-core</artifactId>
- <version>${shardingsphere.version}</version>
- </dependency>
-
- <!-- 使用BASE事务时,需要引入此模块 -->
- <dependency>
- <groupId>org.apache.shardingsphere</groupId>
- <artifactId>sharding-transaction-base-seata-at</artifactId>
- <version>${sharding-sphere.version}</version>
- </dependency>
- <!-- 进行ShardingDataSource的相关配置 -->
- ...
-
- <!-- 开启自动扫描@ShardingTransactionType注解,使用Spring原生的AOP在类和方法上进行增强 -->
- <sharding:tx-type-annotation-driven />
-
- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="shardingDataSource" />
- </bean>
- <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
- <property name="dataSource" ref="shardingDataSource" />
- </bean>
- <tx:annotation-driven />
-
- @ShardingTransactionType(TransactionType.XA) // 支持TransactionType.LOCAL, TransactionType.XA, TransactionType.BASE
- public void insert() {
- jdbcTemplate.execute("INSERT INTO t_order (user_id, status) VALUES (?, ?)", (PreparedStatementCallback<Object>) preparedStatement -> {
- preparedStatement.setObject(1, i);
- preparedStatement.setObject(2, "init");
- preparedStatement.executeUpdate();
- });
- }
- <dependency>
- <groupId>org.apache.shardingsphere</groupId>
- <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
- <version>${shardingsphere.version}</version>
- </dependency>
-
- <!-- 使用XA事务时,需要引入此模块 -->
- <dependency>
- <groupId>org.apache.shardingsphere</groupId>
- <artifactId>sharding-transaction-xa-core</artifactId>
- <version>${shardingsphere.version}</version>
- </dependency>
-
- <!-- 使用BASE事务时,需要引入此模块 -->
- <dependency>
- <groupId>org.apache.shardingsphere</groupId>
- <artifactId>sharding-transaction-base-seata-at</artifactId>
- <version>${sharding-sphere.version}</version>
- </dependency>
- @Configuration
- @EnableTransactionManagement
- public class TransactionConfiguration {
-
- @Bean
- public PlatformTransactionManager txManager(final DataSource dataSource) {
- return new DataSourceTransactionManager(dataSource);
- }
-
- @Bean
- public JdbcTemplate jdbcTemplate(final DataSource dataSource) {
- return new JdbcTemplate(dataSource);
- }
- }
- @Transactional
- @ShardingTransactionType(TransactionType.XA) // 支持TransactionType.LOCAL, TransactionType.XA, TransactionType.BASE
- public void insert() {
- jdbcTemplate.execute("INSERT INTO t_order (user_id, status) VALUES (?, ?)", (PreparedStatementCallback<Object>) preparedStatement -> {
- preparedStatement.setObject(1, i);
- preparedStatement.setObject(2, "init");
- preparedStatement.executeUpdate();
- });
- }
本篇文章只是对ShardingSphere做了简单的介绍及部分功能的使用,想要详细深入的学习及使用可以参考官网:Index of /document/legacy/4.x
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。