Sharding-JDBC(ShardingSphere)多数据库与springboot集成 -- 读写分离

Sharding-JDBC(ShardingSphere)作为分布式数据库中间件,在Java的JDBC层提供的额外服务。它使用客户端直连数据库,以jar包形式提供服务。引入sharding-jdbc-spring-boot-starter可以快速完成与springboot的集成; 但是默认情况下只能支持到一个数据库,如果支持多数据库,需要做部分扩展;本文记录支持多数据库所做的扩展。

引入依赖

1
2
3
4
5
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.1</version>
</dependency>

扩展部分

  • 实现EnvironmentAware接口 ,在方法setEnvironment解析properties配置可以获取所有配置信息

  • 获取以spring.ydal为前缀的所有数据库配置

    1
    Map<String, Object> databases = PropertyUtil.handle(environment, "spring.ydal" , Map.class);
  • 构造每个数据库的数据库的MasterSlave数据源

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     Map<String, Object> dataSourceProps = PropertyUtil.handle(environment, "spring.eldal." + dataBaseName+"datasource", Map.class);
    Preconditions.checkState(!dataSourceProps.isEmpty(), "Wrong datasource properties!");

    DataSource datasource = DataSourceUtil.getDataSource(dataSourceProps.get("type").toString(), dataSourceProps);
    Optional<DataSourcePropertiesSetter> dataSourcePropertiesSetter = DataSourcePropertiesSetterHolder.getDataSourcePropertiesSetterByType(dataSourceProps.get("type").toString());
    if (dataSourcePropertiesSetter.isPresent()) {
    dataSourcePropertiesSetter.get().propertiesSet(environment, prefix, dataSourceName, datasource);
    }

    masterSlaveRule = PropertyUtil.handle(environment, "spring.eldal." + dataBaseName+".masterslave", YamlMasterSlaveRuleConfiguration.class);
    MasterSlaveRuleConfiguration msConfig = new MasterSlaveRuleConfigurationYamlSwapper().swap(masterSlaveRule);

    Properties dsProps = PropertyUtil.handle(environment, "spring.eldal." + dataBaseName+".props", Properties.class);
    MasterSlaveDataSourceFactory.createDataSource(datasource, msConfig, dsProps)

禁用ShardingSphere的Springboot的自动配置

实现该扩展后以jar包的形式提供出去供多个项目使用,所以我们必须在jar里面禁用ShardingSphere的Springboot的自动配置;可以实现如下接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class YdalAutoConfigurationImportFilter implements AutoConfigurationImportFilter {
private static final Set<String> SHOULD_SKIP = new HashSet<>(
Arrays.asList("org.apache.shardingsphere.shardingjdbc.spring.boot.SpringBootConfiguration"));
@Override
public boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) {
boolean[] matches = new boolean[autoConfigurationClasses.length];

for(int i = 0; i< autoConfigurationClasses.length; i++) {
matches[i] = !SHOULD_SKIP.contains(autoConfigurationClasses[i]);
}
return matches;
}
}

  • YdalAutoConfigurationImportFilter加入META-INF/spring.factories
最后
yhzhu wechat
欢迎您扫一扫上面的微信公众号,联系我