侧边栏壁纸
博主头像
码森林博主等级

一起走进码森林,享受编程的乐趣,发现科技的魅力,创造智能的未来!

  • 累计撰写 145 篇文章
  • 累计创建 73 个标签
  • 累计收到 4 条评论

目 录CONTENT

文章目录

ShardingSphere4.1.1 | Sharding-JDBC实现垂直分库

码森林
2022-11-15 / 0 评论 / 0 点赞 / 184 阅读 / 1,456 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-11-15,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

前言

前文已经介绍了ShardingSphere及相关组件,Sharding-JDBC是ShardingSphere的第一个产品,也是ShardingSphere的前身。本文主要通过代码实例介绍如何使用Sharding-JDBC 。

第一篇文章介绍是官网对于sharding-jdbc的解释和介绍,其实说的直白一点,就是包含了分库分表功能的JDBC,因此我们可以直接把sharding-jdbc当做普通的jdbc来进行使用。

本系列文章项目基于SpringBoot构建,采用ShardingSphere v4.1.1,由于5.X版本还在公测,可能存在诸多Bug。

Sharding-JDBC 实现垂直分库

1、环境构建

创建一个SpringBoot项目,引入如下依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>cn.zwqh</groupId>
        <artifactId>sharding-sphere-4.1.1</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>cn.zwqh</groupId>
    <artifactId>sharding-sphere-demo-3</artifactId>
    <version>${parent.version}</version>

    <packaging>jar</packaging>

    <name>sharding-sphere-demo-3</name>
    <description>Demo project for Spring Boot</description>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>cn.zwqh.shardingspheredemo3.ShardingSphereDemo3Application</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

2、创建数据库ds0、ds1,在ds0创建数据表t_order,在ds1创建数据表t_user

CREATE TABLE `t_order` (
  `order_id` bigint NOT NULL COMMENT '订单id',
  `order_type` tinyint(1) DEFAULT NULL COMMENT '订单类型',
  `user_id` int DEFAULT NULL COMMENT '用户id',
  `order_amount` decimal(10,2) DEFAULT NULL COMMENT '订单金额',
  PRIMARY KEY (`order_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

CREATE TABLE `t_user` (
  `user_id` int NOT NULL COMMENT '用户id',
  `user_name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户名称',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

3、分片规则

将不同表的数据插入到不同的库中。

4、创建实体类

@Data
public class Orders {
    private Integer orderId;
    private Integer orderType;
    private Integer userId;
    private Double orderAmount;
}

@Data
public class UserEntity {
    private Integer userId;
    private String userName;
}

5、创建Mapper类

@Mapper
public interface OrdersMapper {

    @Insert("insert into orders(order_id,order_type,user_id,order_amount) values(#{orderId},#{orderType},#{userId},#{orderAmount})")
    void insertOrder(Orders orders);
}

@Mapper
public interface UserMapper {

    @Insert("insert into users(user_id,user_name) values(#{userId},#{userName})")
    void insertUser(UserEntity userEntity);

}

6、创建配置文件

serser.port=8080

spring.application.name=spring-boot-shardingsphere

#配置数据源的名称
spring.shardingsphere.datasource.names=ds0,ds1

#配置数据源的具体内容,
spring.shardingsphere.datasource.ds0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds0.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.ds0.url=jdbc:mysql://127.0.0.1:3306/ds0?serverTimezone=UTC
spring.shardingsphere.datasource.ds0.username=root
spring.shardingsphere.datasource.ds0.password=123456

spring.shardingsphere.datasource.ds1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.ds1.url=jdbc:mysql://127.0.0.1:3306/ds1?serverTimezone=UTC
spring.shardingsphere.datasource.ds1.username=root
spring.shardingsphere.datasource.ds1.password=123456

#配置order表所在的数据节点
spring.shardingsphere.sharding.tables.orders.actual-data-nodes=ds0.t_order
#user表的主键生成策略
spring.shardingsphere.sharding.tables.orders.key-generator.column=order_id
spring.shardingsphere.sharding.tables.orders.key-generator.type=SNOWFLAKE
#指定user表分片的策略
spring.shardingsphere.sharding.tables.orders.table-strategy.inline.sharding-column=order_id
spring.shardingsphere.sharding.tables.orders.table-strategy.inline.algorithm-expression=t_order
#配置user表所在的数据节点
spring.shardingsphere.sharding.tables.users.actual-data-nodes=ds1.t_user
#user表的主键生成策略
spring.shardingsphere.sharding.tables.users.key-generator.column=user_id
spring.shardingsphere.sharding.tables.users.key-generator.type=SNOWFLAKE
#指定user表分片的策略
spring.shardingsphere.sharding.tables.users.table-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.tables.users.table-strategy.inline.algorithm-expression=t_user
#显示sql
spring.shardingsphere.props.sql.show=true

7、创建测试类

@SpringBootTest
public class OrderTests {

    @Resource
    private OrdersMapper ordersMapper;

  @Test
    public void addOrder() {
        for (int i = 1; i <= 10; i++) {
            Orders orders = new Orders();
            orders.setOrderId(i);
            orders.setUserId(i);
            orders.setOrderType(i % 2);
            orders.setOrderAmount(1000.0 * i);
            ordersMapper.insertOrder(orders);
        }
    }

}


@SpringBootTest
public class UserTests {

    @Resource
    private UserMapper userMapper;

    @Test
    public void insertUser() {
        for (int i = 1; i <= 10; i++) {
            UserEntity userEntity = new UserEntity();
            userEntity.setUserId(i);
            userEntity.setUserName("user" + i);
            userMapper.insertUser(userEntity);
        }
    }
}

8、执行结果

和预期一样,orders数据插入到了ds0.t_order,users数据插入到了ds1.t_user。

9、SNOWFLAKE

把新增操作中的主键order_id去除,新增时会自动生成唯一ID插入。

源码地址

github

码云

0

评论区