使用 Java API

引入 Maven 依赖

  1. <dependency>
  2. <groupId>org.apache.shardingsphere</groupId>
  3. <artifactId>shardingsphere-jdbc-governance</artifactId>
  4. <version>${shardingsphere.version}</version>
  5. </dependency>
  6. <!-- 使用 ZooKeeper 时,需要引入此模块 -->
  7. <dependency>
  8. <groupId>org.apache.shardingsphere</groupId>
  9. <artifactId>shardingsphere-governance-repository-zookeeper-curator</artifactId>
  10. <version>${shardingsphere.version}</version>
  11. </dependency>
  12. <!-- 使用 Etcd 时,需要引入此模块 -->
  13. <dependency>
  14. <groupId>org.apache.shardingsphere</groupId>
  15. <artifactId>shardingsphere-governance-repository-etcd</artifactId>
  16. <version>${shardingsphere.version}</version>
  17. </dependency>

规则配置

以下示例将 ZooKeeper 作为配置中心和注册中心。

  1. // 省略配置数据源以及规则
  2. // ...
  3. // 配置注册中心
  4. RegistryCenterConfiguration registryCenterConfig = new RegistryCenterConfiguration("Zookeeper", "localhost:2181", new Properties());
  5. // 配置治理
  6. GovernanceConfiguration governanceConfiguration = new GovernanceConfiguration("governance-sharding-data-source", registryCenterConfig, true);
  7. // 创建 GovernanceShardingSphereDataSource
  8. DataSource dataSource = GovernanceShardingSphereDataSourceFactory.createDataSource(governanceConfiguration);

使用 GovernanceShardingSphereDataSource

通过 GovernanceShardingSphereDataSourceFactory 工厂创建的 GovernanceShardingSphereDataSource 实现自 JDBC 的标准接口 DataSource。 可通过 DataSource 选择使用原生 JDBC,或JPA, MyBatis 等 ORM 框架。

以原生 JDBC 使用方式为例:

  1. DataSource dataSource = GovernanceShardingSphereDataSourceFactory.createDataSource(governanceConfiguration);
  2. 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=?";
  3. try (
  4. Connection conn = dataSource.getConnection();
  5. PreparedStatement ps = conn.prepareStatement(sql)) {
  6. ps.setInt(1, 10);
  7. ps.setInt(2, 1000);
  8. try (ResultSet rs = preparedStatement.executeQuery()) {
  9. while(rs.next()) {
  10. // ...
  11. }
  12. }
  13. }