Mybatis + Sharding JDBC分库分表

1  水平分表 

1.1需求说明

        使用Sharding-JDBC完成对订单表的水平分表,通过快速入门程序的开发,快速体验Sharding-JDBC的使用 方法。 人工创建两张表,t_order_1和t_order_2,这两张表是订单表拆分后的表,通过Sharding-Jdbc向订单表插入数据, 按照一定的分片规则,主键为偶数的进入t_order_1,另一部分数据进入t_order_2,通过Sharding-Jdbc 查询数 据,根据 SQL语句的内容从t_order_1或t_order_2查询数据。

1.2.环境搭建

1.2.1 环境说明

操作系统:Win10

数据库:MySQL-5.7.25

JDK:64位 jdk1.8.0_201

应用框架:spring-boot-2.1.3.RELEASE,Mybatis3.5.0
Sharding-JDBC:sharding-jdbc-spring-boot-starter-4.0.0-RC1

1.2.2 创建数据库

创建订单库order_db

CREATE DATABASE `order_db` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';

在order_db中创建t_order_1、t_order_2表

DROP TABLE IF EXISTS `t_order_1`;
CREATE TABLE `t_order_1` (
`order_id` bigint(20) NOT NULL COMMENT '订单id',
`price` decimal(10, 2) NOT NULL COMMENT '订单价格',
`user_id` bigint(20) NOT NULL COMMENT '下单用户id',
`status` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '订单状态',
PRIMARY KEY (`order_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
DROP TABLE IF EXISTS `t_order_2`;
CREATE TABLE `t_order_2` (
`order_id` bigint(20) NOT NULL COMMENT '订单id',
`price` decimal(10, 2) NOT NULL COMMENT '订单价格',
`user_id` bigint(20) NOT NULL COMMENT '下单用户id',
`status` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '订单状态',
PRIMARY KEY (`order_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

1.2.3.引入maven依赖

引入 sharding-jdbc和SpringBoot整合的Jar包:

<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>sharding‐jdbc‐spring‐boot‐starter</artifactId>
    <version>4.0.0‐RC1</version>
</dependency>

1.3 编写程序

1.3.1 分片规则配置

分片规则配置是sharding-jdbc进行对分库分表操作的重要依据,配置内容包括:数据源、主键生成策略、分片策 略等。

在application.properties中配置

server.port=56081
spring.application.name = sharding‐jdbc‐simple‐demo

server.servlet.context‐path = /sharding‐jdbc‐simple‐demo
spring.http.encoding.enabled = true
spring.http.encoding.charset = UTF‐8
spring.http.encoding.force = true
spring.main.allow‐bean‐definition‐overriding = true
mybatis.configuration.map‐underscore‐to‐camel‐case = true
# 以下是分片规则配置
# 定义数据源
spring.shardingsphere.datasource.names = m1
spring.shardingsphere.datasource.m1.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m1.driver‐class‐name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m1.url = jdbc:mysql://localhost:3306/order_db?useUnicode=true
spring.shardingsphere.datasource.m1.username = root
spring.shardingsphere.datasource.m1.password = root
# 指定t_order表的数据分布情况,配置数据节点
spring.shardingsphere.sharding.tables.t_order.actual‐data‐nodes = m1.t_order_$‐>{1..2}
# 指定t_order表的主键生成策略为SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order.key‐generator.column=order_id
spring.shardingsphere.sharding.tables.t_order.key‐generator.type=SNOWFLAKE

# 指定t_order表的分片策略,分片策略包括分片键和分片算法
spring.shardingsphere.sharding.tables.t_order.table‐strategy.inline.sharding‐column = order_id
spring.shardingsphere.sharding.tables.t_order.table‐strategy.inline.algorithm‐expression =
t_order_$‐>{order_id % 2 + 1}
# 打开sql输出日志
spring.shardingsphere.props.sql.show = true
swagger.enable = true
logging.level.root = info
logging.level.org.springframework.web = info
logging.level.com.itheima.dbsharding = debug
logging.level.druid.sql = debug

1.3.2.数据操作

@Mapper
@Component
public interface OrderDao {
    /**
    * 新增订单
    * @param price 订单价格
    * @param userId 用户id
    * @param status 订单状态
    * @return
    */
    @Insert("insert into t_order(price,user_id,status) value(#{price},#{userId},#            
    {status})")
    int insertOrder(@Param("price") BigDecimal price, @Param("userId")Long userId,
                    @Param("status")String status);
    /**
    * 根据id列表查询多个订单
    * @param orderIds 订单id列表
    * @return
    */
    @Select({"<script>" +
    "select " +
    " * " +
    " from t_order t" +
    " where t.order_id in " +
    "<foreach collection='orderIds' item='id' open='(' separator=',' close=')'>" +
    " #{id} " +
    "</foreach>"+
    "</script>"})
    List<Map> selectOrderbyIds(@Param("orderIds")List<Long> orderIds);
}

1.3.3.测试

编写单元测试:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ShardingJdbcSimpleDemoBootstrap.class})
public class OrderDaoTest {
    @Autowired
    private OrderDao orderDao;
    @Test
    public void testInsertOrder(){
    for (int i = 0 ; i<10; i++){
        orderDao.insertOrder(new BigDecimal((i+1)*5),1L,"WAIT_PAY");
    }
    }
    @Test
    public void testSelectOrderbyIds(){
    List<Long> ids = new ArrayList<>();
    ids.add(373771636085620736L);
    ids.add(373771635804602369L);
    List<Map> maps = orderDao.selectOrderbyIds(ids);
    System.out.println(maps);
    }
}

2. 水平分库

水平分库是把同一个表的数据按一定规则拆到不同的数据库中,每个库可以放在不同的服务器 上。

2.1 创建数据库

将原有order_db库拆分为order_db_1、order_db_2

 2.2 分片规则修改

由于数据库拆分了两个,这里需要配置两个数据源。

分库需要配置分库的策略,和分表策略的意义类似,通过分库策略实现数据操作针对分库的数据库进行操作。

server.port=56081

spring.application.name = sharding-jdbc-simple-demo

server.servlet.context-path = /sharding-jdbc-simple-demo
spring.http.encoding.enabled = true
spring.http.encoding.charset = UTF-8
spring.http.encoding.force = true

spring.main.allow-bean-definition-overriding = true

mybatis.configuration.map-underscore-to-camel-case = true

#sharding-jdbc分片规则配置
#数据源
spring.shardingsphere.datasource.names = m1,m2

spring.shardingsphere.datasource.m1.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m1.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m1.url = jdbc:mysql://localhost:3306/order_db_1?useUnicode=true
spring.shardingsphere.datasource.m1.username = root
spring.shardingsphere.datasource.m1.password = root

spring.shardingsphere.datasource.m2.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m2.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m2.url = jdbc:mysql://localhost:3306/order_db_2?useUnicode=true
spring.shardingsphere.datasource.m2.username = root
spring.shardingsphere.datasource.m2.password = root


# 分库策略,以user_id为分片键,分片策略为user_id % 2 + 1,user_id为偶数操作m1数据源,否则操作m2。
spring.shardingsphere.sharding.tables.t_order.database-strategy.inline.sharding-column = user_id
spring.shardingsphere.sharding.tables.t_order.database-strategy.inline.algorithm-expression = m$->{user_id % 2 + 1}

# 指定t_order表的数据分布情况,配置数据节点 m1.t_order_1,m1.t_order_2,m2.t_order_1,m2.t_order_2
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes = m$->{1..2}.t_order_$->{1..2}

# 指定t_order表的主键生成策略为SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order.key-generator.column=order_id
spring.shardingsphere.sharding.tables.t_order.key-generator.type=SNOWFLAKE

# 指定t_order表的分片策略,分片策略包括分片键和分片算法
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.sharding-column = order_id
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.algorithm-expression = t_order_$->{order_id % 2 + 1}


# 打开sql输出日志
spring.shardingsphere.props.sql.show = true

swagger.enable = true

logging.level.root = info
logging.level.org.springframework.web = info
logging.level.com.itheima.dbsharding  = debug
logging.level.druid.sql = debug

2.3 插入测试

修改testInsertOrder方法,插入数据中包含不同的user_id

@Test
public void testInsertOrder(){
    for (int i = 0 ; i<10; i++){
        orderDao.insertOrder(new BigDecimal((i+1)*5),1L,"WAIT_PAY");
    }
    for (int i = 0 ; i<10; i++){
        orderDao.insertOrder(new BigDecimal((i+1)*10),2L,"WAIT_PAY");
    }
}

2.4 查询测试

调用快速入门的查询接口进行测试:

List<Map> selectOrderbyIds(@Param("orderIds")List<Long> orderIds);
@Test
public void testSelectOrderbyUserAndIds(){
    List<Long> orderIds = new ArrayList<>();
    orderIds.add(373422416644276224L);
    orderIds.add(373422415830581248L);
    //查询条件中包括分库的键user_id
    int user_id = 1;
    List<Map> orders = orderDao.selectOrderbyUserAndIds(user_id,orderIds);
    JSONArray jsonOrders = new JSONArray(orders);
    System.out.println(jsonOrders);
}

3. 垂直分库

垂直分库是指按照业务将表进行分类,分布到不同的数据库上面,每个库可以放在不同的服务器 上,它的核心理念是专库专用。

3.1 创建数据库

创建数据库user_db

CREATE DATABASE `user_db` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';

在user_db中创建t_user表

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`user_id` bigint(20) NOT NULL COMMENT '用户id',
`fullname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户姓名',
`user_type` char(1) DEFAULT NULL COMMENT '用户类型',
PRIMARY KEY (`user_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

 3.2 在Sharding-JDBC规则中修改

server.port=56081

spring.application.name = sharding-jdbc-simple-demo

server.servlet.context-path = /sharding-jdbc-simple-demo
spring.http.encoding.enabled = true
spring.http.encoding.charset = UTF-8
spring.http.encoding.force = true

spring.main.allow-bean-definition-overriding = true

mybatis.configuration.map-underscore-to-camel-case = true

#sharding-jdbc分片规则配置
#数据源
spring.shardingsphere.datasource.names = m0,m1,m2

spring.shardingsphere.datasource.m0.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m0.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m0.url = jdbc:mysql://localhost:3306/user_db?useUnicode=true
spring.shardingsphere.datasource.m0.username = root
spring.shardingsphere.datasource.m0.password = root


spring.shardingsphere.datasource.m1.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m1.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m1.url = jdbc:mysql://localhost:3306/order_db_1?useUnicode=true
spring.shardingsphere.datasource.m1.username = root
spring.shardingsphere.datasource.m1.password = root

spring.shardingsphere.datasource.m2.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m2.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m2.url = jdbc:mysql://localhost:3306/order_db_2?useUnicode=true
spring.shardingsphere.datasource.m2.username = root
spring.shardingsphere.datasource.m2.password = root


# 分库策略,以user_id为分片键,分片策略为user_id % 2 + 1,user_id为偶数操作m1数据源,否则操作m2。
spring.shardingsphere.sharding.tables.t_order.database-strategy.inline.sharding-column = user_id
spring.shardingsphere.sharding.tables.t_order.database-strategy.inline.algorithm-expression = m$->{user_id % 2 + 1}

# 指定t_order表的数据分布情况,配置数据节点 m1.t_order_1,m1.t_order_2,m2.t_order_1,m2.t_order_2
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes = m$->{1..2}.t_order_$->{1..2}
spring.shardingsphere.sharding.tables.t_user.actual-data-nodes = m$->{0}.t_user

# 指定t_order表的主键生成策略为SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order.key-generator.column=order_id
spring.shardingsphere.sharding.tables.t_order.key-generator.type=SNOWFLAKE

# 指定t_order表的分片策略,分片策略包括分片键和分片算法
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.sharding-column = order_id
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.algorithm-expression = t_order_$->{order_id % 2 + 1}

spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.sharding-column = user_id
spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.algorithm-expression = t_user


# 打开sql输出日志
spring.shardingsphere.props.sql.show = true

swagger.enable = true

logging.level.root = info
logging.level.org.springframework.web = info
logging.level.com.itheima.dbsharding  = debug
logging.level.druid.sql = debug

3.3 数据操作

新增UserDao:

@Mapper
@Component
public interface UserDao {
    /**
    * 新增用户
    * @param userId 用户id
    * @param fullname 用户姓名
    * @return
    */
    @Insert("insert into t_user(user_id, fullname) value(#{userId},#{fullname})")
    int insertUser(@Param("userId")Long userId,@Param("fullname")String fullname);
    /**
    * 根据id列表查询多个用户
    * @param userIds 用户id列表
    * @return
    */
    @Select({"<script>",
    " select",
    " * ",
    " from t_user t ",
    " where t.user_id in",
    "<foreach collection='userIds' item='id' open='(' separator=',' close=')'>",
    "#{id}",
    "</foreach>",
    "</script>"
    })
    List<Map> selectUserbyIds(@Param("userIds")List<Long> userIds);

}

3.4 测试

新增单元测试方法

@Test
public void testInsertUser(){
    for (int i = 0 ; i<10; i++){
        Long id = i + 1L;
        userDao.insertUser(id,"姓名"+ id );
    }
}
@Test
public void testSelectUserbyIds(){
    List<Long> userIds = new ArrayList<>();
    userIds.add(1L);
    userIds.add(2L);
    List<Map> users = userDao.selectUserbyIds(userIds);
    System.out.println(users);
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值