spring boot 实现分库分表 (yml 方式)

本贴最后更新于 2022 天前,其中的信息可能已经时移俗易

spring boot 实现分库分表 (yml 方式)

数据源分片策略使用单独 yml 文件配置,通过 Java config 方式定义数据源,这种方式比较推荐

源码地址:https://github.com/zousiliang/fast/tree/tag5.0

添加数据:

http://localhost/curPrice/add?createdBy=1&luck=1

查看数据

http://localhost/curPrice/all

创建两个数据库 并同时创建两个表

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

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    945 引用 • 1460 回帖 • 1 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...