【Sharding-Sphere 整合SpringBoot】

Sharding-Jdbc在3.0后改名为Sharding-Sphere。Sharding-Sphere相关资料,请自行网上查阅,这里仅仅介绍了实战相关内容,算是抛砖引玉。

Sharding-Sphere 整合SpringBoot

  • 一、项目准备
  • 二、项目实战
    • 1. pom.xml及application.yml
    • 2. OrderInfoController
    • 3. OrderInfoService
    • 4. OrderInfo
    • 5. OrderInfoMapper
    • 6. USerTablePreciseShardingAlgorithm
  • 三、项目测试
    • 1.利用postman测试接口
    • 2.数据库结果
  • 四、项目结构及源码下载
    • 1.项目结构
    • 2.源码下载

一、项目准备

创建12张order_info表
这里以创建order_info_01为例

CREATE TABLE `order_info_01` (
  `id` varchar(100) NOT NULL,
  `create_date` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

二、项目实战

1. pom.xml及application.yml


<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">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.5.4version>
        <relativePath/>
    parent>
    <groupId>com.bstgroupId>
    <artifactId>shardartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>shardname>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
        <sharding-sphere.version>4.1.1sharding-sphere.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

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

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

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>


        
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
            <version>3.8version>
        dependency>

        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>2.0.1version>
        dependency>

        
        <dependency>
            <groupId>com.github.pagehelpergroupId>
            <artifactId>pagehelperartifactId>
            <version>5.3.2version>
        dependency>

        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.22version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>

        
        
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>1.7.25version>
        dependency>


        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
        dependency>

        
        <dependency>
            <groupId>org.apache.shardingspheregroupId>
            <artifactId>sharding-jdbc-spring-boot-starterartifactId>
            <version>${sharding-sphere.version}version>
        dependency>

        <dependency>
            <groupId>com.xiaoleilugroupId>
            <artifactId>hutool-allartifactId>
            <version>3.2.0version>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.3.1version>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>
server:
  port: 8080
  tomcat:
    uri-encoding: UTF-8
    max-threads: 1000
    min-spare-threads: 10
logging:
  level:
    com.taguan: debug
spring:
  shardingsphere:
    datasource:
      names: db1
      db1: # 数据库
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test?useUnicode=true
        username: root
        password: root1234
    sharding:
      tables:
        order_info:  #
          # 配置表的分布,表的策略
          #actual-data-nodes:
          actual-data-nodes: db1.order_info_0$->{1..9},db1.order_info_1$->{0..2}
          # 指定tg_weld_after_rule_表 主键id 生成策略为 SNOWFLAKE
          key-generator:
            column: id
            type: SNOWFLAKE
          # 指定分片策略
          table-strategy:
            #            inline:
            ##              约定id值是偶数添加到tg_weld_after_rule_0表,如果id是奇数添加到tg_weld_after_rule_1表
            #              sharding-column: id
            #              algorithm-expression: tg_weld_after_rule_$->{id%2}
            standard:
              #根据年月份进行分表,分表规则自定义handler
              sharding-column: create_date
              precise-algorithm-class-name: com.huahua.shard.myShard.USerTablePreciseShardingAlgorithm
    props:
      # 打开sql输出日志
      sql:
        show: true


2. OrderInfoController

@RestController
public class OrderInfoController {

    @Autowired
    private OrderInfoService orderInfoService;

    @RequestMapping("add")
    public String add() throws ParseException {
        return orderInfoService.add();
    }


    @RequestMapping("get")
    @ResponseBody
    public Object get() {
        return orderInfoService.get();
    }
}

3. OrderInfoService

@Service
public class OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    public String add() throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setId(UUID.randomUUID().toString());
            int a = RandomUtils.nextInt(1, 9);
            String dateStr = "2024-09-1" + a;
            Date date = formatter.parse(dateStr);
            orderInfo.setCreateDate(date);
            orderInfoMapper.insert(orderInfo);

            orderInfo.setId(UUID.randomUUID().toString());
            String dateS = "2024-10-1" + a;
            orderInfo.setCreateDate(formatter.parse(dateS));
            orderInfoMapper.insert(orderInfo);

            orderInfo.setId(UUID.randomUUID().toString());
            String date2S = "2024-11-1" + a;
            orderInfo.setCreateDate(formatter.parse(date2S));
            orderInfoMapper.insert(orderInfo);

            orderInfo.setId(UUID.randomUUID().toString());
            String date22S = "2024-12-1" + a;
            orderInfo.setCreateDate(formatter.parse(date22S));
            orderInfoMapper.insert(orderInfo);

        }
        return "0";
    }

    public Object get() {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        //wrapper.eq("create_date","2024-08-08");
        return orderInfoMapper.selectList(wrapper);
    }
}

4. OrderInfo

@Data
public class OrderInfo {
    private String id;
    private Date createDate;
}

5. OrderInfoMapper

public interface OrderInfoMapper extends BaseMapper<OrderInfo> {
}

6. USerTablePreciseShardingAlgorithm

自定义算法规则

public class USerTablePreciseShardingAlgorithm implements PreciseShardingAlgorithm<Date> {

    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Date> preciseShardingValue) {
        try {
            String tableName = preciseShardingValue.getLogicTableName();
            String dataTime;
            if (preciseShardingValue.getValue() != null) {
                dataTime = formatter.format(preciseShardingValue.getValue());
            } else {
                throw new IllegalArgumentException("没有匹配到库");
            }
            // 按照月份,拼接数据库表名
            return tableName.concat("_").concat(dataTime.substring(5, 7));
        } catch (Exception e) {
            throw new IllegalArgumentException("没有匹配到库:" + preciseShardingValue.getValue());
        }
    }
}

三、项目测试

1.利用postman测试接口

【Sharding-Sphere 整合SpringBoot】_第1张图片

2.数据库结果

【Sharding-Sphere 整合SpringBoot】_第2张图片

四、项目结构及源码下载

1.项目结构

【Sharding-Sphere 整合SpringBoot】_第3张图片

2.源码下载

点我下载,欢迎Star哦~~

你可能感兴趣的:(SpringBoot,spring,boot,java,Sharding-JDBC,Sharding-Sphere)