使用 Spring Boot Starter

引入 Maven 依赖

  1. <dependency>
  2. <groupId>org.apache.shardingsphere</groupId>
  3. <artifactId>shardingsphere-jdbc-governance-spring-boot-starter</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>

规则配置

  1. spring.shardingsphere.governance.name=governance-spring-boot-shardingsphere-test
  2. spring.shardingsphere.governance.registry-center.type=Zookeeper
  3. spring.shardingsphere.governance.registry-center.server-lists=localhost:2181
  4. spring.shardingsphere.governance.overwrite=true

在 Spring 中使用 GovernanceShardingSphereDataSource

直接通过注入的方式即可使用 GovernanceShardingSphereDataSource;或者将 GovernanceShardingSphereDataSource 配置在JPA, MyBatis 等 ORM 框架中配合使用。

  1. @Resource
  2. private DataSource dataSource;