shradingSphere读写分离配置
shardngSphere 的读写分离配置
主要讲解shardngSphere 的读写分离配置与基础内容讲解
maven依赖配置
shardingSphere 版本 5.0.0-alpha,
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.0.0-alpha</version>
</dependency>
yaml的数据源配置与策略配置
版本5与版本4的配置完全不一样
数据库配置是一主一从,由于是读写分离,数据库从库同步主库数据需要运维配置
spring:
shardingsphere:
sharding:
default-database-strategy: # 默认数据库策略
standard:
sharding-column: id
sharding-algorithm-name: database-default
enabled: true
props:
sql-show: true
datasource:
common:
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
names: master, slave1
master:
url: jdbc:mysql://192.168.212.147:3306/db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2b8&allowPublicKeyRetrieval=true
username: root
password: 123456
slave1:
url: jdbc:mysql://192.168.212.148:3306/db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2b8&allowPublicKeyRetrieval=true
username: root
password: 123456
rules:
replica-query: # 读写分离数据源配置
dataSources:
ms: # 该数据源在配置表的时候使用
primaryDataSourceName: master
replicaDataSourceNames:
- slave1
loadBalancerName: round
loadBalancers:
round:
type: ROUND_ROBIN # 类型有轮询与数据 ROUND_ROBIN 是轮询
props: # 负载均衡器没有配置参数,不配置却会有错
enabled: true
sharding:
key-generators: # 分布式主键策略
snowflake: # 策略名自定义
type: SNOWFLAKE
props:
worker-id: 123
sharding-algorithms: # 数据分片策略
table-order-id:
type: INLINE
props:
algorithm-expression: tb_order$->{order_id % 5}
database-default:
type: INLINE
props:
algorithm-expression: master
tables: # 表配置
tb_order:
actual-data-nodes: ms.tb_order$->{0..4} # 配置读写分离数据源
table-strategy:
standard:
sharding-column: order_id
sharding-algorithm-name: table-order-id
key-generate-strategy: #上面配置的雪花算法主键生成策略
column: order_id
key-generator-name: snowflake
需配置事务管理器与jdbcTemplate
springboot 启动时不自动加载默认数据源,使用sharding的数据源
springboot 启动时不自动加载默认默认事务管理,由于有分布式的业务,需要分布式事务管理(这不细讲)
jdbcTemplate 提供给执行sql的框架使用如 jpa等等
@Configuration
@Slf4j
public class DatabaseConfig {
@Resource
private DataSource dataSource;
@Bean
public PlatformTransactionManager txManager() {
return new DataSourceTransactionManager(dataSource);
}
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource);
}
}
剔除springboot 默认加载数据源与默认事务管理器
@SpringBootApplication(
exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class
}
)
读写测试
众所周知,有逻辑表与物理表的概念
- 在 master 主库插入数据
- 在 slave1 从库查询数据
读写分离场景
对于2C端产品,日活增加而导致数据库的查询压力增大,为了避免整个系统受到影响就采用读写分离。读流量增大的时候,可以继续让从库横向扩展。
官网SEO场景,官网日活用户或许并不会很大,但需要抗住各个搜索引擎的数据摘取,或是网站的访问攻击,避免数据库读请求太多而影响到写的功能(读请求太多,CPU被读请求占满,无法进行写操作),应考采用读写分离方案。
总结
主要目的还是让多个数据库分担流量压力,亦可以采取缓存,限流,降级等等策略来完成,但数据库是最底层最根本的服务支撑,数据库的高可用也是最重要的。