Spring Boot整合Sharding Sphere

发布时间 2023-08-03 00:18:29作者: 摆烂ing
  1. 加依赖
<dependency>
	<groupId>org.apache.shardingsphere</groupId>
	<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
	<version>5.1.2</version>
</dependency>
  1. 创建新的配置文件application-sharding.yml,在application.yml中导入新的配置文件
spring:
  # 加载sharding配置文件信息
  profiles:
    include: sharding
  1. 在application-sharding.yml中配置数据源和读写分离
spring:
  shardingsphere:
    # 配置数据源
    datasource:
      names: master, slave01, slave02
      master:
        type: com.zaxxer.hikari.HikariDataSource
        driverClassName: com.mysql.jdbc.Driver
        jdbcUrl: jdbc:mysql://192.168.6.129:3306/gmall_product?useSSL=false&characterEncoding=UTF8
        username: root
        password: 1234
      slave01:
        type: com.zaxxer.hikari.HikariDataSource
        driverClassName: com.mysql.jdbc.Driver
        jdbcUrl: jdbc:mysql://192.168.6.129:3307/gmall_product?useSSL=false&characterEncoding=UTF8
        username: root
        password: 1234
      slave02:
        type: com.zaxxer.hikari.HikariDataSource
        driverClassName: com.mysql.jdbc.Driver
        jdbcUrl: jdbc:mysql://192.168.6.129:3308/gmall_product?useSSL=false&characterEncoding=UTF8
        username: root
        password: 1234
    # 配置读写分离
	rules:
      readwrite-splitting:
        data-sources:
          product-rw-rules:
            type: Static
            props:
              write-data-source-name: master
              read-data-source-names: slave01,slave02
            loadBalancerName: product_lb
        load-balancers:
          product_lb:
            type: ROUND_ROBIN
    props:
      sql-show: true

注:注释掉application.yml配置文件中数据源的相关配置