引入依赖
我本地用的是 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-localshardingsphere:datasource:names:write-ds,read-ds-0write-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=convertToNulltype:com.zaxxer.hikari.HikariDataSourcedriver-class-name:com.mysql.cj.jdbc.Driverusername:rootpassword:nicaiconnectionTimeoutMilliseconds:3000idleTimeoutMilliseconds:60000maxLifetimeMilliseconds:1800000maxPoolSize:50minPoolSize:1maintenanceIntervalMilliseconds:30000read-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=convertToNulltype:com.zaxxer.hikari.HikariDataSourcedriver-class-name:com.mysql.cj.jdbc.Driverusername:rootpassword:nicaiconnectionTimeoutMilliseconds:3000idleTimeoutMilliseconds:60000maxLifetimeMilliseconds:1800000maxPoolSize:50minPoolSize:1maintenanceIntervalMilliseconds:30000rules:readwrite-splitting:data-sources:glapp:write-data-source-name:write-dsread-data-source-names:-read-ds-0load-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:Configurationpropertyname'spring.shardingsphere.datasource.write_ds'isnotvalid:Invalidcharacters:'_'Bean:org.apache.shardingsphere.spring.boot.ShardingSphereAutoConfigurationReason:Canonicalnamesshouldbekebab-case('-'separated),lowercasealpha-numericcharactersandmuststartwithaletterAction:Modify'spring.shardingsphere.datasource.write_ds'sothatitconformstothecanonicalnamesrequirements.
之前把配置文件中的某些名字配置用下划线写了,不行,得用中线。
测试
所有的改动只有以上这么多,还是比较简单的,以下的读库请求打过来时的监控,证明读请求都过来了,写库没有。
这是写库的:
这是读库的:
参考
https://shardingsphere.apache.org/document/5.0.0-beta/