0
点赞
收藏
分享

微信扫一扫

了解HTTP安全标头(HTTP Security Headers)

Gascognya 04-01 14:00 阅读 1

1、shardingsphere 介绍

     Apache ShardingSphere 是一款分布式 SQL 事务和查询引擎,可通过数据分片、弹性伸缩、加密等能力对任意数据库进行增强。官方网站地址Apache ShardingSphere

2、SpringBoot 项目接入

2.1、 maven 添加依赖

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

当然还有添加数据库依赖,看你数据库而定,shardingsphere 支持的数据库请查询官网。

2.2 、 添加配置文件

#是用来定义需要分片的数据源名称

spring.shardingsphere.datasource.names=o1

#  配置连接池

spring.shardingsphere.datasource.o1.type=com.zaxxer.hikari.HikariDataSource

#  数据库驱动

spring.shardingsphere.datasource.o1.driver-class-name=com.mysql.cj.jdbc.Driver

# 数据连接

spring.shardingsphere.datasource.o1.jdbc-url=jdbc:mysql://192.168.10.9:3306/?useUnicode=true&characterEncoding=UTF8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai

# 数据库用户名和密码

spring.shardingsphere.datasource.o1.username=root spring.shardingsphere.datasource.o1.password=root!

spring.shardingsphere.props.sql.show=true

#默认数据源

spring.shardingsphere.sharding.default-data-source-name=o1

# 数据库分表策略

#spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=o1.t_order_$->{2023..2024}$->{1..9},t_order_$->{2023..2024}$->{0..2}

spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=o1.t_order_$->{2023..2024}

# 数据库主键策略

spring.shardingsphere.sharding.tables.t_order.key-generator.column=id spring.shardingsphere.sharding.tables.t_order.key-generator.type=snowflake

#数据库表分表的列

spring.shardingsphere.sharding.tables.t_order.table-strategy.standard.sharding-column=date1

# 分表数据接口实现

spring.shardingsphere.sharding.tables.t_order.table-strategy.standard.precise-algorithm-class-name=com.example.demo.utils.OrderTableShardingAlgorithm 

2.3、分表策略算法实现

代码如下:

@Component
@Slf4j
public class OrderTableShardingAlgorithm implements PreciseShardingAlgorithm<Date> , RangeShardingAlgorithm<Date> {

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Date> preciseShardingValue) {
        //preciseShardingValue就是当前插入的字段值
        //collection 内就是所有的逻辑表
        //获取字段值
        Date time = preciseShardingValue.getValue();
        if(time == null){
            throw new UnsupportedOperationException("prec is null");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        String year =sdf.format(time);
        for (String tableName : collection) {//循环表名已确定使用哪张表
            String name = tableName.substring(8,tableName.length() );
            if(year.equals(name)){
                return tableName;//返回要插入的逻辑表
            }
        }
        return null;
    }
举报

相关推荐

0 条评论