Use Java API

Import Maven Dependency

  1. <dependency>
  2. <groupId>org.apache.shardingsphere</groupId>
  3. <artifactId>shardingsphere-jdbc-core</artifactId>
  4. <version>${shardingsphere.version}</version>
  5. </dependency>
  6. <!-- import if using ZooKeeper -->
  7. <dependency>
  8. <groupId>org.apache.shardingsphere</groupId>
  9. <artifactId>shardingsphere-cluster-mode-repository-zookeeper-curator</artifactId>
  10. <version>${shardingsphere.version}</version>
  11. </dependency>
  12. <!-- import if using Etcd -->
  13. <dependency>
  14. <groupId>org.apache.shardingsphere</groupId>
  15. <artifactId>shardingsphere-cluster-mode-repository-etcd</artifactId>
  16. <version>${shardingsphere.version}</version>
  17. </dependency>

Configure Rule

Using ZooKeeper as config center and registry center for example.

  1. // Omit configure data sources and rule configurations
  2. // ...
  3. // Configure ClusterPersistRepositoryConfig
  4. ClusterPersistRepositoryConfiguration registryCenterConfig = new ClusterPersistRepositoryConfiguration("Zookeeper", "governance-sharding-data-source", "localhost:2181", new Properties());
  5. // Configure Cluster Config
  6. ModeConfiguration modeConfig = new ModeConfiguration("Cluster", registryCenterConfig, true);
  7. // Create ShardingSphereDataSource
  8. DataSource dataSource = ShardingSphereDataSourceFactory.createDataSource(modeConfig);

Use ShardingSphereDataSource

The ShardingSphereDataSource created by ShardingSphereDataSourceFactory implements the standard JDBC DataSource interface. Developer can choose to use native JDBC or ORM frameworks such as JPA or MyBatis through the DataSource.

Take native JDBC usage as an example:

  1. DataSource dataSource = ShardingSphereDataSourceFactory.createDataSource(modeConfig);
  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. }