sharding-jdbc分库分表

1.gradle构建方式加载依赖包

compile group: 'io.shardingsphere', name: 'sharding-jdbc-core', version: '3.0.0'

2.TestSourceConfiguration文件类配置数据库

@Configuration()
@MapperScan(annotationClass = Mapper.class, basePackages = {"com.changan.carbond.sharding.jdbc.mapper"}, sqlSessionFactoryRef = "testSqlSessionFactory")
public class TestSourceConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(TestSourceConfiguration.class);

    @Value("${spring.datasource.test.mybatis.type-aliases-package}")
    private String typeAliasesPackage;

    @Value("${spring.datasource.test.mybatis.mapper-locations}")
    private String mapperLocations;

    @Autowired
    private MybatisConfigurationSupport mybatisConfiguration;

    @Bean
    public WallConfig wallConfig() {
        WallConfig wallConfig = new WallConfig();
        wallConfig.setMultiStatementAllow(true);
        return wallConfig;
    }

    @Bean
    public WallFilter wallFilter() {
        WallFilter wallFilter = new WallFilter();
        wallFilter.setConfig(wallConfig());
        return wallFilter;
    }

    @Bean(name = "testDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.test")
    public DruidDataSource testDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        List<Filter> filters = new ArrayList<>();
        filters.add(wallFilter());
        dataSource.setProxyFilters(filters);
        return dataSource;
    }

    @Bean(name = "testSqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("testDataSource") DruidDataSource dataSource) throws Exception {
        mybatisConfiguration.setTypeAliasesPackage(typeAliasesPackage);
        mybatisConfiguration.setMapperLocations(new String[]{mapperLocations});
        Interceptor[] interceptors = new Interceptor[]{MyBatisInterceptor.getPaginatorInterceptor()};
        return mybatisConfiguration.build(dataSource, interceptors);
    }

    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(testDataSource());
    }

}

3.TestShardingSourceConfiguration文件类分库配置

@Configuration()
@MapperScan(basePackages = "com.changan.carbond.sharding.jdbc.sharding", sqlSessionFactoryRef = "testShardingSqlSessionFactory")
public class TestShardingSourceConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(TestShardingSourceConfiguration.class);
    /**
     * sharding jdbc 扫描的mapper文件路径
     */
    @Value("${spring.datasource.test-sharding.mybatis.mapper-locations}")
    private String mapperLocations;

    /**
     * 表的规则配置,每个表都应该有一个配置方法
     *
     * @return {@link TableRuleConfiguration}
     */
    private static TableRuleConfiguration getCarTableRuleConfiguration() {
        TableRuleConfiguration carTableRuleConfig = new TableRuleConfiguration();
        // 对表car添加车辆
        carTableRuleConfig.setLogicTable("car");
        // ============== 配置分库 + 分表策略 =====================

        // 配置表car的分库策略为 NoneShardingStrategyConfiguration 不分库
        carTableRuleConfig.setDatabaseShardingStrategyConfig(new NoneShardingStrategyConfiguration());
        // 配置表car的分表策略为 按 create_at 分表,并且使用 YearMonthTablePreciseShardingAlgorithm 按 年月 分表策略
        carTableRuleConfig.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("create_at", new YearMonthTablePreciseShardingAlgorithm()));

        // 可自行写代码进行初始化
        // 获取已存在的数据库表列表

        Date now = new Date();
        String[] strings = DateUtil.monthBetween(now, DateUtil.parseDate("2019-08-01"));
        StringBuilder dataNodes = new StringBuilder("sharding_jdbc.car");
        for (String string : strings) {
            dataNodes.append(",sharding_jdbc.car_");
            dataNodes.append(string);
        }

        carTableRuleConfig.setActualDataNodes(dataNodes.toString());
        // 表主键字段
        carTableRuleConfig.setKeyGeneratorColumnName("id");
        return carTableRuleConfig;
    }

    /**
     * sharding jdbc 数据源配置, 此处引用的dataSouce在 com.changan.carbond.config.datasouce.TestSourceConfiguration 中进行了定义
     *
     * @param dataSource
     * @return
     * @throws SQLException
     */
    @Bean(name = "testShardingDataSource")
    public DataSource testShardingDataSource(@Qualifier("testDataSource") DataSource dataSource) throws SQLException {
        // 配置分片规则
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();

        // 添加需要分表的表信息 及 配置表规则
        shardingRuleConfig.getTableRuleConfigs().add(getCarTableRuleConfiguration());

        // 数据源设置
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        dataSourceMap.put("sharding_jdbc", dataSource);

        // 属性设置
        Properties properties = new Properties();
        properties.setProperty("sql.show", "true");

        return ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfig, new HashMap<>(), properties);
    }

    /**
     * 此处引用的dataSource 为 分表的dataSource 同 88行的 bean定义保持一致
     */
    @Bean(name = "testShardingSqlSessionFactory")
    public SqlSessionFactory testShardingSqlSessionFactory(@Qualifier("testShardingDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        try {
            factoryBean.getObject().getConfiguration().addInterceptor(MyBatisInterceptor.getPaginatorInterceptor());
            return factoryBean.getObject();
        } catch (Exception e) {
            throw new RuntimeException("Mybatis初始化工厂异常", e);
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值