ShardingSphere JDBC 分库实现多数据库源

本文介绍了如何使用ShardingSphere JDBC 5.0.0结合Spring Boot和Mybatis Plus,实现数据库多数据源的需求。通过自定义分库策略,将表table1映射到数据库demo1,表table2映射到数据库demo2,sharding_table根据传入参数动态选择数据源。关键代码包括数据源配置、自定义分库策略和测试验证,展示了ShardingSphere JDBC的灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介

基于Shardingsphere JDBC 5.0.0版本,利用Sharding分库实现日常开始中的数据库多数据源使用需求,结合Spring Boot 和 Mybatis Plus

数据源需求说明

数据库初始语句如下:

create database demo1;
create database demo2;

create table `demo1`.table1 (
    id int
);

create table `demo2`.table2 (
    id int
);

create table `demo1`.sharding_table (
    id int
);

create table `demo2`.sharding_table (
    id int
);

insert into `demo1`.sharding_table (id) values(1);
insert into `demo2`.sharding_table (id) values(1);

两个数据库,数据库1有表:table1、sharding_table

数据库2有表:table2、sharding_table

要求如下:

  • 当访问表 table1 时,访问数据库 demo1
  • 当访问表 table2 时,访问数据库 demo2
  • 当访问表 sharding_table 时,根据自定义的传入参数,访问对应的数据,本篇文章,将要访问的数据源存入ThreadLocal中,获取后访问对应的数据源

关键代码示例

完整代码GitHub地址:https://github.com/lw1243925457/JAVA-000/tree/main/code/shardingsphere/shardingdb

定义数据源

配置ShardingSphere JDBC数据源,关键代码如下:

配置如下,定义了连个数据源,最后的rules是标识表table1到数据源db0访问,表table2到数据源db1访问

# shardingSphere 分库设置
shardingsphere:
  # 配置真实数据源
  datasources:
    # 数据库1
    db0:
      jdbcurl: ${
   
   DB1_URL:jdbc:mysql://127.0.0.1:3306/demo1?useUnicode=true&serverTimezone=UTC}
      username: ${
   
   DB1_USER:root}
      password: ${
   
   DB1_PASS:root}
    # 数据库2
    db1:
      jdbcurl: ${
   
   DB2_URL:jdbc:mysql://127.0.0.1:3306/demo2?useUnicode=true&serverTimezone=UTC}
      username: ${
   
   DB2_USER:root}
      password: ${
   
   DB2_PASS:root}
  rules:
    table1: db0
    table2: db1

如果使用ShardingSphere的yaml文件配置,暂时还没有找到如何使用环境变量的方式,不方便修改,所有使用Java代码直接进行配置

@Slf4j
@Configuration
public class ShardingDataSourceMybatisPlusConfig extends MybatisPlusAutoConfiguration {
   
   

    private final MultipleDbConfig multipleDbConfig;

    @Primary
    @Bean("dataSource")
    public DataSource getDataSource() throws SQLException {
   
   
        // 配置真实数据源
        Map<String, MultipleDbConfig.DbSource> dbs = multipleDbConfig.getDatasources();
        Map<String, DataSource> dataSourceMap = new HashMap<>(dbs.size());
        for (String dbName: dbs.keySet()) {
   
   
            MultipleDbConfig.DbSource dbConfig = dbs.get(dbName);
            HikariDataSource dataSource = new HikariDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setJdbcUrl(dbConfig.getJdbcUrl());
            dataSource.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值