7,sharding-jdbc入门-配置默认数据源

文章介绍了如何在Sharding-JDBC中使用默认数据源来简化大量表的配置,当找不到特定数据节点时,操作会自动转向默认数据源。测试代码展示了如何在未配置分片规则的情况下,通过默认数据源进行数据操作。

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

 当一个数据库中有大量的表,如果每个表都配置数据节点,代码变得非常繁琐,这时可以使用配置默认数据源,当sharding-jdbc找不到数据节点的时候会找默认数据源下的数据节点,省区了繁琐的配置

执行sql

-- 构建数据
create database default_db character set utf8;
use default_db;
-- 构建表
create table tb_log (
    id bigint primary key ,
    info varchar(30)
);

在test2文件中加入代码

spring.shardingsphere.datasource.names=ds1,ds2,udb,defdb
# 数据库连接池类名称
spring.shardingsphere.datasource.defdb.type=com.alibaba.druid.pool.DruidDataSource
# 数据库驱动类名
spring.shardingsphere.datasource.defdb.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据库 url 连接
spring.shardingsphere.datasource.defdb.url=jdbc:mysql://localhost:3306/default_db?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
# 数据库用户名
spring.shardingsphere.datasource.defdb.username=root
# 数据库密码
spring.shardingsphere.datasource.defdb.password=root123

#spring.shardingsphere.sharding.default-data-source-name= #未配置分片规则的表将通过默认数据源定位
spring.shardingsphere.sharding.default-data-source-name=defdb

java测试代码

package com.itheima.sharding;

import com.itheima.sharding.entity.TDict;
import com.itheima.sharding.entity.TOrder;
import com.itheima.sharding.entity.TUser;
import com.itheima.sharding.entity.TbLog;
import com.itheima.sharding.mapper.TDictMapper;
import com.itheima.sharding.mapper.TOrderMapper;
import com.itheima.sharding.mapper.TUserMapper;
import com.itheima.sharding.mapper.TbLogMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.math.BigDecimal;
import java.util.Random;

@SpringBootTest
public class MyTest {
    @Autowired
    private TbLogMapper tbLogMapper;
    /**
     * 测试默认数据源
     *  对于没有做分片处理的操作,则会直接访问默认数据源处理
     */
    @Test
    public void test5(){
        TbLog log = TbLog.builder().id(2l).info("aaa").build();
        tbLogMapper.insert(log);
    }
}

运行完查看结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲代码的翠花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值