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);
}
}
}