spring boot 实现分库分表 (yml 方式)
数据源分片策略使用单独 yml 文件配置,通过 Java config 方式定义数据源,这种方式比较推荐
源码地址:https://github.com/zousiliang/fast/tree/tag5.0
添加数据:
http://localhost/curPrice/add?createdBy=1&luck=1
查看数据
创建两个数据库 并同时创建两个表
pom.xml:
<dependency>
<groupId>io.shardingjdbc</groupId>
<artifactId>sharding-jdbc-core</artifactId>
<version>2.0.3</version>
</dependency>
DataSourceConfig 文件:
@Configuration
public class DataSourceConfig {
@Autowired
private Filter statFilter;
private static final String SHARDING_YML_PATH = "dataSource.yml";
/**
* 构建dataSource
* 这里没有使用ShardingDataSourceFactory
* 因为要为durid数据源配置监听Filter
* @return
* @throws SQLException
* @throws IOException
*/
@Bean
public DataSource dataSource() throws SQLException, IOException {
YamlShardingConfiguration config = parse();
ShardingRule rule = config.getShardingRule(Collections.<String, DataSource>emptyMap());
rule.getDataSourceMap().forEach((k,v)->{
DruidDataSource d = (DruidDataSource) v;
d.setProxyFilters(Lists.newArrayList(statFilter));
});
return new ShardingDataSource(rule, config.getShardingRule().getConfigMap(), config.getShardingRule().getProps());
}
/**
* 解析yml
* @return
* @throws IOException
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
private YamlShardingConfiguration parse() throws IOException, FileNotFoundException, UnsupportedEncodingException {
Resource certResource = new ClassPathResource(SHARDING_YML_PATH);
try (
InputStreamReader inputStreamReader = new InputStreamReader(certResource.getInputStream(), "UTF-8")
) {
return new Yaml(new Constructor(YamlShardingConfiguration.class)).loadAs(inputStreamReader, YamlShardingConfiguration.class);
}
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于