spring boot使用经验分享(二)集成sharding-sphere实现分表

MySQL拥有体积小、速度快、成本低、开源等多种优点,而且随着今年的发展mysql性能也有了一定的提升,越来越多的公司在选择数据库的时候,选择使用MySQL。

但是当MySQL中单表数据量达到千万级别的时候,就需要考虑一个问题-分库分表。

网上有各种各样的开源框架,但是其中最为常见的就是sharding-sphere。

一、什么是ShardingSphere?

ShardingSphere是一套开源的分布式数据库中间件解决方案组成的生态圈,它由Sharding-JDBC、Sharding-Proxy和Sharding-Sidecar(计划中)这3款相互独立的产品组成。 他们均提供标准化的数据分片、分布式事务和数据库治理功能,可适用于如Java同构、异构语言、容器、云原生等各种多样化的应用场景。

二、项目中如何运用?

1)首先需要在pom.xml中引入依赖

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

2)application.properties配置

数据库配置
spring.shardingsphere.datasource.names=product #数据库名,可配置多个,用,隔开

spring.shardingsphere.datasource.product.type=com.zaxxer.hikari.HikariDataSource #使用Hikari,性能不错推荐

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

spring.shardingsphere.datasource.product.jdbc-url=jdbc:mysql://localhost:3306/product?useUnicode=true&characterEncoding=utf-8&useSSL=true&autoReconnect=true&serverTimezone=UTC spring.shardingsphere.datasource.product.username=root

spring.shardingsphere.datasource.product.password=123456

spring.shardingsphere.datasource.product.connection-timeout=30000  #超时时间

spring.shardingsphere.datasource.product.minimum-idle=10 #连接池中空闲连接最小数量,为了性能考虑,不建议设置此值,而是让HikariCP把连接池当做固定大小的处理,默认minimumIdle与maximumPoolSize一样。

spring.shardingsphere.datasource.product.max-lifetime=110000 #一个连接在连接池中的存活时间,默认是1800000(30分钟)

spring.shardingsphere.datasource.product.maximum-pool-size=10 #连接池中允许的最大连接数。缺省值:10;推荐的公式:((core_count * 2) + effective_spindle_count(磁盘列阵中的硬盘数))

spring.shardingsphere.datasource.product.pool-name=HikariPool-product

spring.shardingsphere.datasource.product.connectionTestQuery=SELECT 1

spring.shardingsphere.props.sql.show=true #是否开启SQL显示

分表配置

spring.shardingsphere.sharding.tables.order_log.actual-data-nodes=product.order_log_$->{0..15} #order_log_0-order_log_15

spring.shardingsphere.sharding.tables.order_log.table-strategy.inline.sharding-column=order_id #根据订单号分表

spring.shardingsphere.sharding.tables.order_log.table-strategy.inline.algorithm-expression=order_log_$->{order_id % 16}

spring.shardingsphere.sharding.tables.order_log.key-generator.column=id  #生成分布式id,防止主键重复

spring.shardingsphere.sharding.tables.order_log.key-generator.type=SNOWFLAKE #使用snowflake算法

spring.shardingsphere.sharding.tables.order_log.key-generator.props.worker.id=${worker.id} #snowflake的worker.id,可以根据hostname启动时计算

发布了43 篇原创文章 · 获赞 0 · 访问量 3912

猜你喜欢

转载自blog.csdn.net/zhangdx001/article/details/105013348