Background

ShardingSphere-JDBC supports all database JDBC drivers and connection pools.

This section describes how to configure data sources through the JAVA API.

Procedure

1. Import Maven dependency.

  1. <dependency>
  2. <groupId>org.apache.shardingsphere</groupId>
  3. <artifactId>shardingsphere-jdbc</artifactId>
  4. <version>${latest.release.version}</version>
  5. </dependency>

Notice: Please change ${latest.release.version} to the actual version.

Sample

  1. ModeConfiguration modeConfig = // Build running mode
  2. Map<String, DataSource> dataSourceMap = createDataSources();
  3. Collection<RuleConfiguration> ruleConfigs = ... // Build specific rules
  4. Properties props = ... // Build attribute configuration
  5. DataSource dataSource = ShardingSphereDataSourceFactory.createDataSource(databaseName, modeConfig, dataSourceMap, ruleConfigs, props);
  6. private Map<String, DataSource> createDataSources() {
  7. Map<String, DataSource> dataSourceMap = new HashMap<>();
  8. // Configure the 1st data source
  9. HikariDataSource dataSource1 = new HikariDataSource();
  10. dataSource1.setDriverClassName("com.mysql.jdbc.Driver");
  11. dataSource1.setJdbcUrl("jdbc:mysql://localhost:3306/ds_1");
  12. dataSource1.setUsername("root");
  13. dataSource1.setPassword("");
  14. dataSourceMap.put("ds_1", dataSource1);
  15. // Configure the 2nd data source
  16. HikariDataSource dataSource2 = new HikariDataSource();
  17. dataSource2.setDriverClassName("com.mysql.jdbc.Driver");
  18. dataSource2.setJdbcUrl("jdbc:mysql://localhost:3306/ds_2");
  19. dataSource2.setUsername("root");
  20. dataSource2.setPassword("");
  21. dataSourceMap.put("ds_2", dataSource2);
  22. }