springboot 整合 shardingsphere-jdbc MybatisPlus 行表达式水平分库分表

·  阅读 879

在项目pom.xml添加配置

     <properties>
        <java.version>8</java.version>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <mybatisplus.boot.starter.version>3.4.2</mybatisplus.boot.starter.version>
        <sharding-jdbc.version>4.1.1</sharding-jdbc.version>
        <mysql.version>8.0.27</mysql.version>
    </properties>
复制代码
      <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--mybatis plus和springboot整合-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatisplus.boot.starter.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
复制代码

application.properties文件配置

spring.application.name=demo-sharding-jdbc
server.port=8080



# 打印执行的数据库以及语句
spring.shardingsphere.props.sql.show=true

#配置数据源 db0 多个数据源逗号隔开 例如: ds0,ds1
spring.shardingsphere.datasource.names=ds0,ds1

# 配置数据库1参数
spring.shardingsphere.datasource.ds0.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds0.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.ds0.jdbc-url=jdbc:mysql://192.168.2.66:3306/shop_order_0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
spring.shardingsphere.datasource.ds0.username=root
spring.shardingsphere.datasource.ds0.password=123456



# 配置数据库2参数
spring.shardingsphere.datasource.ds1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.ds1.jdbc-url=jdbc:mysql://192.168.2.66:3306/shop_order_1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
spring.shardingsphere.datasource.ds1.username=root
spring.shardingsphere.datasource.ds1.password=123456



#配置分库规则
spring.shardingsphere.sharding.tables.product_order.database-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.tables.product_order.database-strategy.inline.algorithm-expression=ds$->{user_id % 2}


#配置workid
spring.shardingsphere.sharding.tables.product_order.key-generator.props.worker.id=1

#id生成策略
spring.shardingsphere.sharding.tables.product_order.key-generator.column=id
spring.shardingsphere.sharding.tables.product_order.key-generator.type=SNOWFLAKE

#配置数据节点
spring.shardingsphere.sharding.tables.product_order.actual-data-nodes=ds$->{0..1}.product_order_$->{0..1}

# 指定product_order表的分片策略,分片策略包括【分片键和分片算法】
spring.shardingsphere.sharding.tables.product_order.table-strategy.inline.sharding-column=id
spring.shardingsphere.sharding.tables.product_order.table-strategy.inline.algorithm-expression=product_order_$->{id % 2}

复制代码

表结构

CREATE TABLE `product_order_1` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `out_trade_no` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '订单唯一标识',
  `state` varchar(11) COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'NEW 未支付订单,PAY已经支付订单,CANCEL超时取消订单',
  `create_time` datetime DEFAULT NULL COMMENT '订单生成时间',
  `pay_amount` decimal(16,2) DEFAULT NULL COMMENT '订单实际支付价格',
  `nickname` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '昵称',
  `user_id` bigint(20) DEFAULT NULL COMMENT '用户id',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC;
复制代码

数据库表结构图

image.png

ProductOrderMapper 操作类

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.demo.shardingspherejdbcdemo.model.ProductOrderDO;

/**
 * 订单操作dao类
 */
public interface ProductOrderMapper extends BaseMapper<ProductOrderDO> {
}
复制代码

ProductOrderDO 实体类


import java.util.Date;

@Data
@TableName("product_order")
public class ProductOrderDO {
    /**
     * 订单id
     */
    private Long id;
    /**
     * 交易流水号
     */
    private String outTradeNo;
    /**
     * 状态
     */
    private String state;
    /**
     * 创建时间
     */
    private Date createTime;
    /**
     * 支付金额
     */
    private Double payAmount;
    /**
     * 用户昵称
     */
    private String nickname;
    /***
     * 用户id
     */
    private Long userId;

}
复制代码

springboot 启动类添加注解

@MapperScan("mapper所在路径")
@EnableTransactionManagement
复制代码

测试添加订单数据

image.png

@SpringBootTest
class ShardingsphereJdbcDemoApplicationTests {
    @Autowired
    private ProductOrderMapper productOrderMapper;
    @Test
    void onlyProductSaveTest() {
        //单个库 水平分表
        Random random  = new Random();
        for(int i = 0 ; i < 10; i ++){
            ProductOrderDO productOrderDO = new ProductOrderDO();
//            productOrderDO.setId(0L);
            productOrderDO.setOutTradeNo(UUID.randomUUID().toString().replace("-",""));
            productOrderDO.setState("NEW");
            productOrderDO.setCreateTime(new Date());
            productOrderDO.setPayAmount(Double.valueOf(100+i));
            productOrderDO.setNickname(String.format("用户[%s]",i+""));
            productOrderDO.setUserId(Long.valueOf(random.nextInt(100)));

            productOrderMapper.insert(productOrderDO);
        }
    }

}
复制代码

插入的订单数据

shop_order_0.product_order_0

image.png

shop_order_0.product_order_1

image.png

shop_order_1.product_order_0

image.png

shop_order_1.product_order_1

image.png

分类:
后端
标签:
分类:
后端
标签:
收藏成功!
已添加到「」, 点击更改