Use Spring Namespace

Import Maven Dependency

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

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:cluster="http://shardingsphere.apache.org/schema/shardingsphere/mode-repository/cluster"
  4. xmlns:shardingsphere="http://shardingsphere.apache.org/schema/shardingsphere/datasource"
  5. xmlns="http://www.springframework.org/schema/beans"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://shardingsphere.apache.org/schema/shardingsphere/mode-repository/cluster
  9. http://shardingsphere.apache.org/schema/shardingsphere/mode-repository/cluster/repository.xsd
  10. http://shardingsphere.apache.org/schema/shardingsphere/datasource
  11. http://shardingsphere.apache.org/schema/shardingsphere/datasource/datasource.xsd">
  12. <cluster:repository id="clusterRepository" type="ZooKeeper" namespace="regCenter" server-lists="localhost:2181">
  13. <props>
  14. <prop key="max-retries">3</prop>
  15. <prop key="operation-timeout-milliseconds">3000</prop>
  16. </props>
  17. </cluster:repository>
  18. <shardingsphere:data-source id="shardingDatabasesTablesDataSource" data-source-names="demo_ds_0, demo_ds_1" rule-refs="shardingRule">
  19. <shardingsphere:mode type="Cluster" repository-ref="clusterRepository" overwrite="true"/>
  20. </shardingsphere:data-source>
  21. <shardingsphere:data-source id="replicaQueryDataSource" data-source-names="demo_primary_ds, demo_replica_ds_0, demo_replica_ds_1" rule-refs="replicaQueryRule">
  22. <shardingsphere:mode type="Cluster" repository-ref="clusterRepository" overwrite="true"/>
  23. </shardingsphere:data-source>
  24. <shardingsphere:data-source id="encryptDataSource" data-source-names="demo_ds" rule-refs="encryptRule">
  25. <shardingsphere:mode type="Cluster" repository-ref="clusterRepository" overwrite="true"/>
  26. </shardingsphere:data-source>
  27. </beans>

Use ShardingSphereDataSource in Spring

ShardingSphereDataSource can be used directly by injection; or configure ShardingSphereDataSource in ORM frameworks such as JPA or MyBatis.

  1. @Resource
  2. private DataSource dataSource;