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