上一篇我们用 ShardingSphere-Proxy实现了读写分离
这一次我们用 ShardingSphere-JDBC 来实现一下
引入依赖
我本地用的是 springboot 2 的版本,引用的 ShardingSphere-JDBC 的5.0.0-beta
版本
<dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId> <version>5.0.0-beta</version> </dependency>
修改配置文件
spring: profiles: include: common-local shardingsphere: datasource: names: write-ds,read-ds-0 write-ds: jdbcUrl: jdbc:mysql://mysql.local.test.myapp.com:23306/test?allowPublicKeyRetrieval=true&useSSL=false&allowMultiQueries=true&serverTimezone=Asia/Shanghai&useSSL=false&autoReconnect=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.cj.jdbc.Driver username: root password: nicai connectionTimeoutMilliseconds: 3000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 50 minPoolSize: 1 maintenanceIntervalMilliseconds: 30000 read-ds-0: jdbcUrl: jdbc:mysql://mysql.local.test.read1.myall.com:23306/test?allowPublicKeyRetrieval=true&useSSL=false&allowMultiQueries=true&serverTimezone=Asia/Shanghai&useSSL=false&autoReconnect=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.cj.jdbc.Driver username: root password: nicai connectionTimeoutMilliseconds: 3000 idleTimeoutMilliseconds: 60000 maxLifetimeMilliseconds: 1800000 maxPoolSize: 50 minPoolSize: 1 maintenanceIntervalMilliseconds: 30000 rules: readwrite-splitting: data-sources: glapp: write-data-source-name: write-ds read-data-source-names: - read-ds-0 load-balancer-name: roundRobin # 负载均衡算法名称 load-balancers: roundRobin: type: ROUND_ROBIN # 一共两种一种是 RANDOM(随机),一种是 ROUND_ROBIN(轮询)
这里主要根据官网的 property 配置文件转的 yaml 文件,需要注意几点:
- type: com.zaxxer.hikari.HikariDataSource 我用的是 Hikari 连接池,根据你的实际情况来
- driver-class-name: com.mysql.cj.jdbc.Driver 不同 mysql 版本不一样,根据你的实际情况来,我的是 mysql 8.0
- jdbcUrl ,官网上写的是 url, 不对,要写成 jdbcUrl
遇到的问题
Description: Configuration property name 'spring.shardingsphere.datasource.write_ds' is not valid: Invalid characters: '_' Bean: org.apache.shardingsphere.spring.boot.ShardingSphereAutoConfiguration Reason: Canonical names should be kebab-case ('-' separated), lowercase alpha-numeric characters and must start with a letter Action: Modify 'spring.shardingsphere.datasource.write_ds' so that it conforms to the canonical names requirements.
之前把配置文件中的某些名字配置用下划线写了,不行,得用中线。
测试
所有的改动只有以上这么多,还是比较简单的,以下的读库请求打过来时的监控,证明读请求都过来了,写库没有。
这是写库的:
这是读库的: