ShardingSphere-JDBC 4.0.0-RC1 多数据源配置


场景描述:

项目中存在多个数据源配置对应多个数据库连接,其中一个数据源为shardingsphere数据源

POM文件

        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>4.0.0-RC1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-namespace</artifactId>
            <version>4.0.0-RC1</version>
        </dependency>

数据源初始化类

普通数据源初始化

@Configuration
@MapperScan(basePackages = "com.pro.test.dao", sqlSessionTemplateRef = "testSqlSessionTemplate")
public class DataSourcetestConfig {

    @Bean(name = "testDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "testSqlSessionFactory")
    public SqlSessionFactory deviceSqlSessionFactory(@Qualifier("testDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "testSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("testSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

shardingsphere数据源初始化


@Configuration
@MapperScan(basePackages = "com.pro.test2.dao", sqlSessionTemplateRef = "test2SqlSessionTemplate")
public class test2DataSourceConfig {

    @Value("${spring.shardingsphere.datasource.master.username}")
    private String userName;

    @Value("${spring.shardingsphere.datasource.master.url}")
    private String url;

    @Value("${spring.shardingsphere.datasource.master.password}")
    private String userPwd;

    @Value("${spring.shardingsphere.datasource.names}")
    private String dataName;

    @Bean(name = "test2DataSource")
    @Qualifier("test2DataSource")
    public DataSource deviceDataSource() throws SQLException {
        return getShardingDataSource();
    }


    @Bean(name = "test2SqlSessionFactory")
    @Primary
    public SqlSessionFactory deviceSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mybatis/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "test2SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate deviceSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    DataSource getShardingDataSource() throws SQLException {
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
	// 配置分表规则
        shardingRuleConfig.getTableRuleConfigs().add(getTaTable2TableRuleConfiguration());
        shardingRuleConfig.getTableRuleConfigs().add(getTaTable3TableRuleConfiguration());
        shardingRuleConfig.getBindingTableGroups().add("ta_table_2");
        shardingRuleConfig.getBindingTableGroups().add("ta_table_3");

        Properties props = new Properties();
	// 配置shardingsphere是否打印日志 
        props.setProperty("sql.show", "true");
	// 创建数据源
        return ShardingDataSourceFactory.createDataSource(createDataSourceMap(), shardingRuleConfig, props);
    }
	
    // 返回ta_table_2表的分表规则配置
    TableRuleConfiguration getTaTable2TableRuleConfiguration() {
	// 指定数据库及表配置规则
        TableRuleConfiguration result = new TableRuleConfiguration("ta_table_2", "master.ta_table_2_$->{1..16}");
        // 指定主键及自增配置
	result.setKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLAKE", "id"));
	// 指定分表字段及分表规则类  TaTable2Algorithm为自定义分表规则类
        result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("test2_code", new TaTable2Algorithm()));
        return result;
    }
	
    // 返回ta_table_3表的分表规则配置
    TableRuleConfiguration getTaTable3TableRuleConfiguration() {
        TableRuleConfiguration result = new TableRuleConfiguration("ta_table_3", "master.ta_table_3_$->{1..16}"); 
        result.setKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLAKE", "id"));
        result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("test2_code", new TaTable3Algorithm()));
        return result;
    }
	
    private Map<String, DataSource> createDataSourceMap() {
        Map<String, DataSource> result = new HashMap<>();
        DruidDataSource dbs = new DruidDataSource();
        dbs.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
        dbs.setUrl(url);
        dbs.setUsername(userName);
        dbs.setPassword(userPwd);
        result.put(dataName, dbs);
        return result;
    }

}

TaTable2Algorithm类 分表规则

@Component
public class TaTable2Algorithm implements PreciseShardingAlgorithm<String> {
    private static Logger logger = LogManager.getLogger(TaTable2Algorithm.class);
    // 存放分表规则
    public static HashMap<String, String> hashMap = new HashMap<>();


    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {
        logger.debug("打印获取到的表名 " + JSON.toJSONString(collection));
        logger.debug("分表字段 " + JSON.toJSONString(preciseShardingValue));
        String val = "tra_period_2_" + hashMap.get(preciseShardingValue.getValue());
        logger.debug("获取分表表名 " + val);
        for (String name : collection) {
            if (val.equals(name)) {
                return name;
            }
        }
        logger.debug("未能识别出来分表字段 字段值:" + JSON.toJSONString(preciseShardingValue));
        return null;
    }

    @PostConstruct
    public void initSharding() {
        // 执行加载分表规则操作
        logger.info("开始加载分表规则");
    }
}

yml配置文件

spring:
  datasource:
    testdb1:
      type: com.alibaba.druid.pool.DruidDataSource
      driverClassName: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.01:3306/test1?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
      username: root
      password: 123456
      validation-query: SELECT 1
    testdb2:
      type: com.alibaba.druid.pool.DruidDataSource
      driverClassName: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.01:3306/test2?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8
      username: root
      password: 123456
      validation-query: SELECT 1
  shardingsphere:
    datasource:
      names: master
      master:
        driver-class-name: com.mysql.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://127.0.01:3306/test3?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
        username: root
        password: 123456


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM