在我们使用Sharding-JDBC实现分库分表时,更多的表是不需要分库分表的,此时我们需要配置默认数据库,让不需要分库分表的表,使用默认数据源。

springboot版本:2.7.1

sharding-jdbc版本:4.1.0

Pom主要配置如下:

<!-- ShardingSphere -->
<dependency>
	<groupId>org.apache.shardingsphere</groupId>
	<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
	<version>4.1.0</version>
</dependency>
<dependency>
	<groupId>org.apache.shardingsphere</groupId>
	<artifactId>sharding-core-common</artifactId>
	<version>4.1.0</version>
</dependency>

 yml配置:

server:
  port: 8089
spring:
  application:
    name: subdatabase
  shardingsphere:
    datasource:
      #不需要分表的默认数据源
      subdatabase:
        driver-class-name: com.mysql.cj.jdbc.Driver
        password: root
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://localhost:3306/subdatabase?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
        username: root
      #分库分表的第一个数据源
      subdatabase0:
        driver-class-name: com.mysql.cj.jdbc.Driver
        password: root
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://localhost:3306/subdatabase0?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
        username: root
      #分库分表的第二个数据源
      subdatabase1:
        driver-class-name: com.mysql.cj.jdbc.Driver
        password: root
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://localhost:3306/subdatabase1?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
        username: root
      names: subdatabase,subdatabase0,subdatabase1
    sharding:
      # 指定不需要分表的普通表使用的数据源
      default-data-source-name: subdatabase
      default-database-strategy:
        inline:
          algorithm-expression: subdatabase$->{userId % 2}
          sharding-column: userId
      tables:
        orders:
          actual-data-nodes: subdatabase$->{0..1}.orders$->{0..1}
          key-generator:
            column: userId
            type: SNOWFLAKE
          table-strategy:
            inline:
              algorithm-expression: orders$->{userId % 2}
              sharding-column: userId
    props:
      sql:
        show: true
mybatis:
  mapper-locations: classpath:mapping/*.xml
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐