电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術(shù)文章
文章詳情頁

springboot2+mybatis多種方式實現(xiàn)多數(shù)據(jù)配置方法

瀏覽:2日期:2023-11-26 18:06:05

業(yè)務(wù)系統(tǒng)復(fù)雜程度增加,為了解決數(shù)據(jù)庫I/O瓶頸,很自然會進行拆庫拆表分服務(wù)來應(yīng)對。這就會出現(xiàn)一個系統(tǒng)中可能會訪問多處數(shù)據(jù)庫,需要配置多個數(shù)據(jù)源。

第一種場景:項目服務(wù)從其它多處數(shù)據(jù)庫取基礎(chǔ)數(shù)據(jù)進行業(yè)務(wù)處理,因此各庫之間不會出現(xiàn)重表等情況。

第二種場景:為了減輕寫入壓力進行讀寫分庫,讀走從庫,寫為主庫。此種表名等信息皆為一致。

第三種場景:以上兩種皆有。對于某些業(yè)務(wù)需要大數(shù)據(jù)量的匯總統(tǒng)計,希望不影響正常業(yè)務(wù)必須走從庫(表信息一致),某些配置信息不存在讀寫壓力,出現(xiàn)不分庫(表信息不一致)

項目源代碼:

https://github.com/zzsong/springboot-multiple-datasource.git

有三個目錄:

one: 直接使用多@Bean配置,@MapperScan來路徑區(qū)分讀何庫

two: 使用注解的方式來標(biāo)識走何dataSource,AOP攔截注入動態(tài)數(shù)據(jù)源

third: 使用spring的Bean命名策略進行區(qū)分數(shù)據(jù)來源

項目技術(shù)選型: springBoot2.2.5 + mybatis + druid + mysql

先看主要的pom包

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.5.RELEASE</version> <relativePath/> </parent><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.21</version> </dependency>

application.yml

spring: datasource: druid: core: url: jdbc:mysql:///kc_core?characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource schedule: url: jdbc:mysql:///kc_schedule?characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource

mysql新版本必須帶有serverTimezone,不然會報連接異常。

第一種:通過@MapperScans 掃描匹配相關(guān)的數(shù)據(jù)源

@Configuration@MapperScans({ @MapperScan(basePackages = 'com.zss.one.mapper.core', sqlSessionTemplateRef = 'coreSqlSessionTemplate',sqlSessionFactoryRef = 'coreSqlSessionFactory'), @MapperScan(basePackages = 'com.zss.one.mapper.schedule', sqlSessionTemplateRef = 'scheduleSqlSessionTemplate',sqlSessionFactoryRef = 'scheduleSqlSessionFactory')})public class MybatisOneConfig { @Bean @ConfigurationProperties(prefix = 'spring.datasource.druid.core') public DataSource coreDataSource(){ return DruidDataSourceBuilder.create().build(); } @Bean public SqlSessionFactory coreSqlSessionFactory(@Qualifier('coreDataSource') DataSource coreDataSource) throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(coreDataSource); sessionFactory.getObject().getConfiguration().setJdbcTypeForNull(null); sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true); return sessionFactory.getObject(); } @Bean public SqlSessionTemplate coreSqlSessionTemplate(@Qualifier('coreSqlSessionFactory') SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } //======schedule======== @Bean @ConfigurationProperties(prefix = 'spring.datasource.druid.schedule') public DataSource scheduleDataSource(){ return DruidDataSourceBuilder.create().build(); } @Bean public SqlSessionFactory scheduleSqlSessionFactory(@Qualifier('scheduleDataSource') DataSource coreDataSource) throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(coreDataSource); sessionFactory.getObject().getConfiguration().setJdbcTypeForNull(null); sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true); return sessionFactory.getObject(); } @Bean public SqlSessionTemplate scheduleSqlSessionTemplate(@Qualifier('scheduleSqlSessionFactory') SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); }}

第二種是動態(tài)數(shù)據(jù)源模式,通過AOP切入注解引導(dǎo)使用何數(shù)據(jù)源。用自定義注解@interface來標(biāo)識方法走對應(yīng)的數(shù)據(jù)源。

注意事項:類中的方法再調(diào)用帶數(shù)據(jù)源的方法,不能被AOP切入

@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface TargetDataSource { String value();}

extends spring的動態(tài)DataSource路由來匹配

public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextRouting.getDataSourceName(); }}

@Configuration//@EnableConfigurationProperties(MybatisProperties.class)//不要使用此公共配置,Configuration會破壞相關(guān)dataSource的配置@MapperScan('com.zss.two.mapper')public class MybatisConfig { @Bean @ConfigurationProperties(prefix = 'spring.datasource.druid.core') public DataSource coreDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = 'spring.datasource.druid.schedule') public DataSource scheduleDataSource() { return DruidDataSourceBuilder.create().build(); } @Autowired @Qualifier('coreDataSource') private DataSource coreDataSource; @Autowired @Qualifier('scheduleDataSource') private DataSource scheduleDataSource; @Bean public DynamicDataSource dataSource() { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put(DataSourceConstants.CORE_DATA_SOURCE, coreDataSource); targetDataSources.put(DataSourceConstants.SCHEDULE_DATA_SOURCE, scheduleDataSource); DynamicDataSource dataSource = new DynamicDataSource(); //設(shè)置數(shù)據(jù)源映射 dataSource.setTargetDataSources(targetDataSources);//// 設(shè)置默認數(shù)據(jù)源,當(dāng)無法映射到數(shù)據(jù)源時會使用默認數(shù)據(jù)源 dataSource.setDefaultTargetDataSource(coreDataSource); dataSource.afterPropertiesSet(); return dataSource; } /** * 根據(jù)數(shù)據(jù)源創(chuàng)建SqlSessionFactory */ @Bean public SqlSessionFactory sqlSessionFactory(DynamicDataSource dataSource) throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); sessionFactory.getObject().getConfiguration().setJdbcTypeForNull(null); sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true); return sessionFactory.getObject(); } @Bean public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); }

第三種,自定義Bean命名策略,按beanName進行自動匹配使用數(shù)據(jù)源

@Componentpublic class CoreBeanNameGenerator implements BeanNameGenerator { @Override public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) { return 'core'+ ClassUtils.getShortName(definition.getBeanClassName()); }}@Componentpublic class ScheduleBeanNameGenerator implements BeanNameGenerator { @Override public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) { return 'schedule'+ ClassUtils.getShortName(definition.getBeanClassName()); }}

使用mybatis MapperScannerConfigurer自動掃描,將Mapper接口生成注入到spring

@Bean public MapperScannerConfigurer coreMapperScannerConfig(CoreBeanNameGenerator coreBeanNameGenerator){ MapperScannerConfigurer configurer = new MapperScannerConfigurer(); configurer.setNameGenerator(coreBeanNameGenerator); configurer.setBasePackage('com.zss.third.mapper.core,com.zss.third.mapper.order'); configurer.setSqlSessionFactoryBeanName('coreSqlSessionFactory'); configurer.setSqlSessionTemplateBeanName('coreSqlSessionTemplate'); return configurer; } @Bean public MapperScannerConfigurer scheduleMapperScannerConfig(ScheduleBeanNameGenerator scheduleBeanNameGenerator){ MapperScannerConfigurer configurer = new MapperScannerConfigurer(); configurer.setNameGenerator(scheduleBeanNameGenerator); configurer.setBasePackage('com.zss.third.mapper.schedule,com.zss.third.mapper.order'); configurer.setSqlSessionFactoryBeanName('scheduleSqlSessionFactory'); configurer.setSqlSessionTemplateBeanName('scheduleSqlSessionTemplate'); return configurer; }

到此,三種多數(shù)據(jù)源匹配主要點介紹完,詳細直接下載github項目。 在resources/db含有相關(guān)測試表及數(shù)據(jù)腳本。

到此這篇關(guān)于springboot2+mybatis多種方式實現(xiàn)多數(shù)據(jù)配置方法的文章就介紹到這了,更多相關(guān)springboot2+mybatis 多數(shù)據(jù)內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 【北京写字楼出租_写字楼租赁_办公室出租网/出售】-远行地产官网 | 断桥铝破碎机_发动机破碎机_杂铝破碎机厂家价格-皓星机械 | 轴承振动测量仪电箱-轴承测振动仪器-测试仪厂家-杭州居易电气 | 证券新闻,热播美式保罗1984第二部_腾讯1080p-仁爱影院 | ◆大型吹塑加工|吹塑加工|吹塑代加工|吹塑加工厂|吹塑设备|滚塑加工|滚塑代加工-莱力奇塑业有限公司 | 全自动在线分板机_铣刀式在线分板机_曲线分板机_PCB分板机-东莞市亿协自动化设备有限公司 | 引领中高档酒店加盟_含舍·美素酒店品牌官网 | 液氮罐_液氮容器_自增压液氮罐_杜瓦瓶_班德液氮罐厂家 | 缝纫客| 超声骨密度仪-骨密度检测仪-经颅多普勒-tcd仪_南京科进实业有限公司 | 砂尘试验箱_淋雨试验房_冰水冲击试验箱_IPX9K淋雨试验箱_广州岳信试验设备有限公司 | 选矿设备-新型重选设备-金属矿尾矿重选-青州冠诚重工机械有限公司 | 温湿度记录纸_圆盘_横河记录纸|霍尼韦尔记录仪-广州汤米斯机电设备有限公司 | 半容积式换热器_北京浮动盘管换热器厂家|北京亿丰上达 | 水性漆|墙面漆|木器家具漆|水漆涂料_晨阳水漆官网 | 西安耀程造价培训机构_工程预算实训_广联达实作实操培训 | 深圳公司注册-工商注册公司-千百顺代理记账公司 | 东莞螺杆空压机_永磁变频空压机_节能空压机_空压机工厂批发_深圳螺杆空压机_广州螺杆空压机_东莞空压机_空压机批发_东莞空压机工厂批发_东莞市文颖设备科技有限公司 | 哈尔滨京科脑康神经内科医院-哈尔滨治疗头痛医院-哈尔滨治疗癫痫康复医院 | 陶瓷加热器,履带式加热器-吴江市兴达电热设备厂 | 全自动包装秤_全自动上袋机_全自动套袋机_高位码垛机_全自动包装码垛系统生产线-三维汉界机器(山东)股份有限公司 | 能量回馈_制动单元_电梯节能_能耗制动_深圳市合兴加能科技有限公司 | 发电机价格|发电机组价格|柴油发电机价格|柴油发电机组价格网 | 泡沫消防车_水罐消防车_湖北江南专用特种汽车有限公司 | 冷却塔风机厂家_静音冷却塔风机_冷却塔电机维修更换维修-广东特菱节能空调设备有限公司 | 回转窑-水泥|石灰|冶金-巩义市瑞光金属制品有限责任公司 | 中空玻璃生产线,玻璃加工设备,全自动封胶线,铝条折弯机,双组份打胶机,丁基胶/卧式/立式全自动涂布机,玻璃设备-山东昌盛数控设备有限公司 | 珠海冷却塔降噪维修_冷却塔改造报价_凉水塔风机维修厂家- 广东康明节能空调有限公司 | 磁力抛光机_磁力研磨机_磁力去毛刺机_精密五金零件抛光设备厂家-冠古科技 | 烟气在线监测系统_烟气在线监测仪_扬尘检测仪_空气质量监测站「山东风途物联网」 | 深圳3D打印服务-3D打印加工-手板模型加工厂-悟空打印坊 | 压砖机_电动螺旋压力机_粉末成型压力机_郑州华隆机械tel_0371-60121717 | 直流大电流电源,燃料电池检漏设备-上海政飞| 悬浮拼装地板_幼儿园_篮球场_悬浮拼接地板-山东悬浮拼装地板厂家 | 奇酷教育-Python培训|UI培训|WEB大前端培训|Unity3D培训|HTML5培训|人工智能培训|JAVA开发的教育品牌 | 棉柔巾代加工_洗脸巾oem_一次性毛巾_浴巾生产厂家-杭州禾壹卫品科技有限公司 | 济南货架定做_仓储货架生产厂_重型货架厂_仓库货架批发_济南启力仓储设备有限公司 | 压滤机-洗沙泥浆处理-压泥机-山东创新华一环境工程有限公司 | 河南中专学校|职高|技校招生-河南中职中专网 | 河南卓美创业科技有限公司-河南卓美防雷公司-防雷接地-防雷工程-重庆避雷针-避雷器-防雷检测-避雷带-避雷针-避雷塔、机房防雷、古建筑防雷等-山西防雷公司 | 湖南自考_湖南自学考试网 |