Sharding-JDBC + springBoot 简单水平分库分表

单库分表

pom文件中加入依赖

<!-- mysql 依赖-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<!-- shardingsphere springboot 依赖-->
<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
    <version>4.0.0-RC1</version>
</dependency>

<!-- Mybatis Plus 依赖 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.0.5</version>
</dependency>

<!--lombok 用于生成getter和setter-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

配置数据源和分表策略

在application.properties 中添加配置

# 配置数据源,c1为数据源名称,后边会用到
spring.shardingsphere.datasource.names=c1
# 一个实体类对应两张表,水平分表必须加
spring.main.allow-bean-definition-overriding=true

#数据源具体配置,包含连接池,驱动,地址,用户名和密码
spring.shardingsphere.datasource.c1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.c1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.c1.url=jdbc:mysql://192.168.31.9:3306/school_1?serverTimezone=GMT%2B8
spring.shardingsphere.datasource.c1.username=root
spring.shardingsphere.datasource.c1.password=123456

#指定 course 表分布情况,配置表在哪个数据库里面,表名称都是什么 c1.course_1 ,c1.course_2
spring.shardingsphere.sharding.tables.course.actual-data-nodes=c1.course_$->{1..2}

# 指定 course 表里面主键 id 生成策略 SNOWFLAKE
spring.shardingsphere.sharding.tables.course.key-generator.column=id
spring.shardingsphere.sharding.tables.course.key-generator.type=SNOWFLAKE

# 指定分片策略 id值偶数添加到course_1表,  id是奇数添加到course_2表
spring.shardingsphere.sharding.tables.course.table-strategy.inline.sharding-column=id
spring.shardingsphere.sharding.tables.course.table-strategy.inline.algorithm-expression=course_$->{id % 2 + 1}

# sql打印
spring.shardingsphere.props.sql.show=true

SpringBoot 启动类修改

增加mapper扫描路径

@SpringBootApplication
@MapperScan("com.example.mapper")	//mapper扫描路径
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }

}

创建数据表

create table course_1(
    id  bigint default 0 not null comment '主键' primary key,
    name    varchar(100)     null,
    user_id bigint           null,
    status  int              null
);

create table course_2(
    id  bigint default 0 not null comment '主键' primary key,
    name    varchar(100)     null,
    user_id bigint           null,
    status  int              null
);

实体类配置

package com.example.demo;
import lombok.Data;

/**
 * @author wx
 */
@Data
public class Course {

    private Long id;
    private String name;
    private Long userId;
    private int status;

    public Course(){}

    public Course(String name, Long userId, int status) {
        this.name = name;
        this.userId = userId;
        this.status = status;
    }
}

增加mapper类

package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.Course;
import org.springframework.stereotype.Repository;

/**
 * @author wx
 */
@Repository
public interface CourseMapper extends BaseMapper<Course> {

}

测试类

package com.example.demo;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.example.mapper.CourseMapper;
import com.example.mapper.DictMapper;
import com.example.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author wx
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class ShardingjdbcTest {

    @Autowired
    private CourseMapper courseMapper;

    @Test
    public void addCourse(){
        for (int i = 0; i < 10; i++) {
            courseMapper.insert(new Course("class_1", new Long(i), 1));
        }
    }

    @Test
    public void findCourse(){
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.eq("id", 569286041035341825L);
        Course course = courseMapper.selectOne(wrapper);
        System.err.println(course);
    }
}

增加分库策略

修改application.properties:

根据userId分库,userId为偶数到c1库, userId为奇数到c2库

# 配置多个数据源, c1和c2
spring.shardingsphere.datasource.names=c1,c2
# 一个实体类对应两张表,覆盖
spring.main.allow-bean-definition-overriding=true

#配置数据源具体内容,包含连接池,驱动,地址,用户名和密码
spring.shardingsphere.datasource.c1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.c1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.c1.url=jdbc:mysql://192.168.31.9:3306/school_1?serverTimezone=GMT%2B8
spring.shardingsphere.datasource.c1.username=root
spring.shardingsphere.datasource.c1.password=123456

spring.shardingsphere.datasource.c2.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.c2.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.c2.url=jdbc:mysql://192.168.31.9:3306/school_2?serverTimezone=GMT%2B8
spring.shardingsphere.datasource.c2.username=root
spring.shardingsphere.datasource.c2.password=123456

#指定数据库的分库情况  数据库:c1 c2  数据表:course_1 course_2
spring.shardingsphere.sharding.tables.course.actual-data-nodes=c$->{1..2}.course_$->{1..2}
# 指定 course 表里面主键 id 生成策略 SNOWFLAKE
spring.shardingsphere.sharding.tables.course.key-generator.column=id
spring.shardingsphere.sharding.tables.course.key-generator.type=SNOWFLAKE

# 指定表的分片策略 id值偶数添加到course_1表,  id是奇数添加到course_2表
spring.shardingsphere.sharding.tables.course.table-strategy.inline.sharding-column=idc
spring.shardingsphere.sharding.tables.course.table-strategy.inline.algorithm-expression=course_$->{id % 2 + 1}

#指定数据库的分片策略. userId为偶数到c1库, userId为奇数到c2库
spring.shardingsphere.sharding.tables.course.database-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.tables.course.database-strategy.inline.algorithm-expression=c$->{user_id % 2 + 1}


# sql打印
spring.shardingsphere.props.sql.show=true

新增test方法

@Test
public void findCourse2(){
     QueryWrapper<Course> wrapper = new QueryWrapper<>();
     wrapper.eq("user_id", 3L);
     List<Course> courses = courseMapper.selectList(wrapper);
     courses.forEach(course -> System.err.println(course));
 }

如下打印日志中可以看到查询使用了哪个数据库( Actual SQL: c2 )
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 我可以为你提供一些关于使用SpringBoot ShardingJDBC MyBatis进行分库分表的建议,例如:1. 使用ShardingSphere框架定义数据库分片策略;2. 使用MyBatis实现MyBatis SQL脚本;3. 使用SpringBoot注解的方式定义数据源和ShardingJDBC的配置。 ### 回答2: 使用SpringBoot ShardingJDBCMyBatis可以很方便地实现分库分表功能。首先,ShardingJDBC是一个轻量级的数据库中间件,可以将数据分散到不同的数据库实例中,从而实现分库的效果。其次,MyBatis是一个流行的持久层框架,可以通过XML或注解的方式与数据库进行交互。 在使用SpringBoot ShardingJDBCMyBatis分库分表时,首先需要配置ShardingJDBC的数据源和分片规则。可以通过编写一个配置类来配置分库分表的规则,例如可以根据某个字段的取值来确定数据应该分散到哪个库或表中。配置完成后,就可以在MyBatis的Mapper接口中直接使用分库分表的数据源,从而实现对不同数据库或表的访问。 在编写Mapper接口时,可以使用MyBatis提供的注解或XML方式来编写SQL语句。在SQL语句中,可以使用ShardingJDBC提供的分片键来实现对特定库或表的访问。例如,在需要查询特定表的数据时,可以使用ShardingJDBC提供的Hint注解将查询操作路由到相应的表上。 总的来说,使用SpringBoot ShardingJDBCMyBatis可以实现简单、高效的分库分表功能。通过配置ShardingJDBC的分片规则和使用MyBatis编写SQL语句,可以将数据分散到不同的数据库实例和表中,从而实现了水平扩展和负载均衡的效果。这种方式能够帮助我们提高数据库的性能和容量,从而更好地应对大规模的数据存储需求。 ### 回答3: 使用SpringBoot ShardingJDBC MyBatis可以轻松实现分库分表。 首先,ShardingJDBC是一个分库分表的开源框架,它可以通过数据库中间件实现数据的分散存储。而SpringBoot是一个快速构建项目的框架,可以帮助开发者轻松集成各种组件。 使用SpringBoot ShardingJDBC MyBatis进行分库分表,首先需要配置ShardingJDBC的数据源、分片策略以及分表策略。可以通过配置文件或者编程方式来完成配置。配置数据源时,可以指定多个数据库的连接信息,并使用分片策略将数据分配到不同的数据库中。配置分表策略时,可以指定不同的分表规则,将数据根据一定的规则分散存储在不同的表中。 在具体的业务逻辑中,可以使用MyBatis来操作数据库。MyBatis是一个简化数据库访问的持久层框架,通过编写SQL语句和映射文件,可以轻松实现数据库的增删改查操作。 在访问数据库时,ShardingJDBC会根据配置的分片策略和分表策略,自动将数据路由到指定的数据库和表中。开发者不需要关心数据的具体存储位置,只需要使用MyBatis的API进行数据操作即可。 使用SpringBoot ShardingJDBC MyBatis进行分库分表,可以提高数据库的读写性能,增加数据的存储容量,并且可以实现数据的动态扩容和迁移。此外,由于SpringBootMyBatis的高度集成,开发者可以更加方便地进行开发和维护。 总之,使用SpringBoot ShardingJDBC MyBatis进行分库分表可以帮助开发者更好地管理数据,提升系统的性能和可扩展性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值