在配置文件中,可以使用spring.datasource.name属性来指定数据源的名称。默认情况下,如果没有指定该属性,数据源的名称为dataSource。因此,在配置Sharding数据源和普通数据源时,需要为它们分别指定不同的名称。

在代码中,使用@Qualifier注解来指定要使用的数据源。例如,如果想要使用Sharding数据源,可以在需要使用的地方加上@Qualifier("shardingDataSource")注解,指定数据源名称为shardingDataSource

示例代码:

spring:
  datasource:
    # 配置Sharding数据源
    sharding:
      datasource:
        names: ds0, ds1
        ds0:
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://localhost:3306/db0
          username: root
          password: root
        ds1:
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://localhost:3306/db1
          username: root
          password: root
      # 配置Sharding规则
      sharding-rule:
        tables:
          user:
            actual-data-nodes: ds${0..1}.user_${0..1}
            table-strategy:
              inline:
                sharding-column: user_id
                algorithm-expression: user_${user_id % 2}
            key-generator:
              type: SNOWFLAKE
              column: id
        binding-tables:
          - user
    # 配置普通数据源
    datasource:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/test
      username: root
      password: root
@Service
public class UserService {

    @Autowired
    @Qualifier("shardingDataSource")
    private DataSource shardingDataSource;

    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

    public void addUser(User user) {
        // 使用Sharding数据源
        try (Connection conn = shardingDataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement("INSERT INTO user (user_id, name) VALUES (?, ?)")) {
            pstmt.setLong(1, user.getUserId());
            pstmt.setString(2, user.getName());
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 使用普通数据源
        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement("INSERT INTO log (user_id, action) VALUES (?, ?)")) {
            pstmt.setLong(1, user.getUserId());
            pstmt.setString(2, "add user");
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
``
springboot在yml中配置sharding分表数据源和spring普通数据源怎么切换到sharding数据源

原文地址: https://www.cveoy.top/t/topic/fhxH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录