使用 Spring 命名空间

引入Maven依赖

  1. <dependency>
  2. <groupId>org.apache.shardingsphere</groupId>
  3. <artifactId>shardingsphere-jdbc-governance-spring-namespace</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. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:governance="http://shardingsphere.apache.org/schema/shardingsphere/governance"
  4. xmlns="http://www.springframework.org/schema/beans"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://shardingsphere.apache.org/schema/shardingsphere/governance
  8. http://shardingsphere.apache.org/schema/shardingsphere/governance/governance.xsd">
  9. <util:properties id="instance-properties">
  10. <prop key="max-retries">3</prop>
  11. <prop key="operation-timeout-milliseconds">3000</prop>
  12. </util:properties>
  13. <governance:reg-center id="regCenter" type="Zookeeper" server-lists="localhost:2181" />
  14. <governance:data-source id="shardingDatabasesTablesDataSource" data-source-names="demo_ds_0, demo_ds_1" reg-center-ref="regCenter" config-center-ref="configCenter" rule-refs="shardingRule" overwrite="true" />
  15. <governance:data-source id="replicaQueryDataSource" data-source-names="demo_primary_ds, demo_replica_ds_0, demo_replica_ds_1" reg-center-ref="regCenter" config-center-ref="configCenter" rule-refs="replicaQueryRule" overwrite="true" />
  16. <governance:data-source id="encryptDataSource" data-source-names="demo_ds" reg-center-ref="regCenter" config-center-ref="configCenter" rule-refs="encryptRule" overwrite="true" />
  17. </beans>

在 Spring 中使用 GovernanceShardingSphereDataSource

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

  1. @Resource
  2. private DataSource dataSource;