1. 程式人生 > 實用技巧 >pigx整合sharding jdbc

pigx整合sharding jdbc

pom依賴:

<properties>
        <sharding-sphere.version>4.1.1</sharding-sphere.version>
</properties>


<dependencies>
    <!-- for spring boot -->
    <dependency>
        <groupId>org.apache.shardingsphere</groupId>
        <artifactId>sharding-jdbc-spring-boot-starter</
artifactId> <version>${sharding-sphere.version}</version> </dependency> </dependencies>

nacos:

spring:
  datasource:
   type: com.alibaba.druid.pool.DruidDataSource
   druid:
     driver-class-name: com.mysql.cj.jdbc.Driver
     username: root
     password: root
     url: jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=utf8

改為如下分片配置:

# 資料來源
spring:
  shardingsphere:
    datasource:
      names: ds0, ds1, defaultds
      defaultds:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://pigx-mysql:3306/testdb
        username: root
        password: root
      ds0:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://pigx-mysql:3306/testdb_0
        username: root
        password: root
      ds1:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://pigx-mysql:3306/testdb_1
        username: root
        password: root
    sharding:
      tables:
        test_user:
          actualDataNodes: ds${0..1}.test_user
          databaseStrategy:
            inline:
              shardingColumn: id
              algorithmExpression: ds${id % 2}
          tableStrategy:
            inline:
              shardingColumn: id
              algorithmExpression: test_user
          keyGenerator:
            type: SNOWFLAKE
            column: id
      defaultDataSourceName: defaultds
      defaultTableStrategy:
        none:
      defaultKeyGenerator:
        type: SNOWFLAKE
        column: xxxx_replace_must
    props:
      sql.show: true

在啟動類上把原本Druid的Datasource去掉,不要autoconfigure

@EnableAutoConfiguration(exclude={DruidDataSourceAutoConfigure.class})