ofa使用sharding-jdbc来进行读写分离。
sharding-jdbc本质上也是通过代理数据源,在进行数据库操作时,通过判断操作类型,自动来决定使用哪一个数据源。读写分离支持一主多从配置。
读写分离配置
spring.shardingsphere.enabled=true
spring.shardingsphere.datasource.names=master,slave0,slave1
spring.shardingsphere.datasource.master.type=org.apache.commons.dbcp.BasicDataSource
spring.shardingsphere.datasource.master.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.master.url=jdbc:mysql://localhost:3306/master
spring.shardingsphere.datasource.master.username=root
spring.shardingsphere.datasource.master.password=
spring.shardingsphere.datasource.slave0.type=org.apache.commons.dbcp.BasicDataSource
spring.shardingsphere.datasource.slave0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.slave0.url=jdbc:mysql://localhost:3306/slave0
spring.shardingsphere.datasource.slave0.username=root
spring.shardingsphere.datasource.slave0.password=
spring.shardingsphere.datasource.slave1.type=org.apache.commons.dbcp.BasicDataSource
spring.shardingsphere.datasource.slave1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.slave1.url=jdbc:mysql://localhost:3306/slave1
spring.shardingsphere.datasource.slave1.username=root
spring.shardingsphere.datasource.slave1.password=
spring.shardingsphere.masterslave.name=ms
spring.shardingsphere.masterslave.master-data-source-name=master
spring.shardingsphere.masterslave.slave-data-source-names=slave0,slave1
spring.shardingsphere.props.sql.show=true
ofa使用seata的AT模式解决分布式事务的问题,shardingsphere也支持柔性事务,由于shardingsphere和seata都是通过代理DataSource来进行操作,所以只要将DataSource包装成seata的DataSourceProxy即可。
@SpringBootApplication(exclude = {
DruidDataSourceAutoConfigure.class,
SeataAutoConfig.class
})
排除掉了druid初始化数据源和seata数据源代理配置,交给shardingsphere完成。
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-transaction-base-seata-at</artifactId>
</dependency>
配置应用的id和事务组
client {
application.id = ofa-admin ## 应用唯一id
transaction.service.group = tcc_tx_group ## 所属事务组
}