SpringBoot:多数据源配置——基于拆包配置

2024-06-21 02:48

本文主要是介绍SpringBoot:多数据源配置——基于拆包配置,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

* maven依赖

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.1.RELEASE</version><relativePath/> <!-- lookup parent from repository -->
</parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 整合freemarker --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency><!-- log4j --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j</artifactId></dependency><!-- aop --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><!-- fastJson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.32</version></dependency><!-- lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!-- mybatis --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version></dependency><!-- mysql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>
</dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins>
</build>

一,多数据源配置

        同一个项目有时候可能会涉及多个数据源,从不同的数据源分别进行CRUD操作;在同一个容器中进行不同的数据库操作,需要考虑多数据源配置;

       本篇基于拆包方式进行多数据源配置,不同的数据源独享mapper下某一分包进行数据库操作,DataSource配置会自动扫描调用包路径进行数据源配置;

       多数据库源配置只是个人尝试,不做企业开发参考;相对于下一篇AOP注解切换数据源,更倾向于通过拆包进行控制,有助于规范化管理,虽然AOP相对更加灵活!

二,项目配置

1,整体构成

    * java代码

    * 配置文件

2,application.properties

### mapper.xml存储路径
mybatis.mapper-locations=classpath:com.gupao.springboot.*.mapper.*/*.xml### MYSQL_First数据源配置
spring.datasource.first.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.first.jdbc-url=jdbc:mysql://localhost:3306/first?characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.first.username=root
spring.datasource.first.password=123456### MYSQL_First数据源配置
spring.datasource.second.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.second.jdbc-url=jdbc:mysql://localhost:3306/second?characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.second.username=root
spring.datasource.second.password=123456

3,数据源注册

    * MYSQL_FIRST数据源注册

package com.gupao.springboot.datasourceprop.config;import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;import javax.sql.DataSource;/*** FirstDataSource数据源** @author pj_zhang* @create 2018-12-28 10:06**/
// 注册到SpringBoot容器中
@Configuration
// MYSQL_FIRST扫描mapper.first包下数据层
@MapperScan(basePackages = "com.gupao.springboot.*.mapper.first", sqlSessionFactoryRef = "firstSqlSessionFactory")
public class FirstDataSourceConfig {/*** 配置FirstDataSource数据源** @return*/@Bean(name = "firstDataSource")@ConfigurationProperties(prefix = "spring.datasource.first")public DataSource firstDataSource() {return DataSourceBuilder.create().build();}/*** 配置SqlSessionFactory** @param dataSource* @return* @throws Exception*/@Bean(name = "firstSqlSessionFactory")public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dataSource);return sqlSessionFactoryBean.getObject();}/*** 数据库事务** @param dataSource* @return*/@Bean(name = "firstTransactionManager")public DataSourceTransactionManager firstTransactionManager(@Qualifier("firstDataSource") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}/*** 配置SqlSessionTemplate** @param sqlSessionFactory* @return*/@Bean(name = "firstSqlSessionTemplate")public SqlSessionTemplate firstSqlSessionTemplate(@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {return new SqlSessionTemplate(sqlSessionFactory);}}

    * MYSQL_SECOND数据源注册

package com.gupao.springboot.datasourceprop.config;import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;import javax.sql.DataSource;/*** secondDataSource数据源** @author pj_zhang* @create 2018-12-28 10:06**/
// 注册到SpringBoot容器中
@Configuration
// MYSQL_SECOND扫描mepper.second包下数据层
@MapperScan(basePackages = "com.gupao.springboot.*.mapper.second", sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDataSourceConfig {/*** 配置secondDataSource数据源** @return*/@Bean(name = "secondDataSource")@ConfigurationProperties(prefix = "spring.datasource.second")public DataSource secondDataSource() {return DataSourceBuilder.create().build();}/*** 配置SqlSessionFactory** @param dataSource* @return* @throws Exception*/@Bean(name = "secondSqlSessionFactory")public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dataSource);return sqlSessionFactoryBean.getObject();}/*** 数据库事务** @param dataSource* @return*/@Bean(name = "secondTransactionManager")public DataSourceTransactionManager secondTransactionManager(@Qualifier("secondDataSource") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}/*** 配置SqlSessionTemplate** @param sqlSessionFactory* @return*/@Bean(name = "secondSqlSessionTemplate")public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {return new SqlSessionTemplate(sqlSessionFactory);}}

4,Controller层

package com.gupao.springboot.datasourceprop.controller;import com.gupao.springboot.datasourceprop.service.IDataSourcePropService;
import com.gupao.springboot.entitys.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;/*** @author pj_zhang* @create 2018-12-28 10:42**/
@Slf4j
@RestController
public class DataSourcePropController {@Autowiredprivate IDataSourcePropService dataSourcePropService;/*** 向MYSQL_FIRST插入数据** @param userName* @param password* @return*/@RequestMapping("/firstInsert")public Integer firstInsert(String userName, String password) {UserVO userVO = new UserVO();userVO.setUserName(userName);userVO.setPassword(password);return dataSourcePropService.insertFirstUserLst(userVO);}/*** 向MYSQL_SECOND插入数据** @param userName* @param password* @return*/@RequestMapping("/secondInsert")public Integer secondInsert(String userName, String password) {UserVO userVO = new UserVO();userVO.setUserName(userName);userVO.setPassword(password);return dataSourcePropService.insertSecondUserLst(userVO);}/*** 查询MYSQL_FIRST数据** @return*/@RequestMapping("/firstPropSelect")public List<UserVO> findFirstData() {return dataSourcePropService.findFirstData();}/*** 查询MYSQL_SECOND数据** @return*/@RequestMapping("/secondPropSelect")public List<UserVO> findSecondData() {return dataSourcePropService.findSecondData();}}

5,Service层

    * Service层接口

package com.gupao.springboot.datasourceprop.service;import com.gupao.springboot.entitys.UserVO;import java.util.List;/*** @author pj_zhang* @create 2018-12-28 10:50**/
public interface IDataSourcePropService {/*** 保存数据-MYSQL_FIRST** @param userVO* @return*/Integer insertFirstUserLst(UserVO userVO);/*** 保存数据-MYSQL_SECOND** @param userVO* @return*/Integer insertSecondUserLst(UserVO userVO);/*** 查询数据-MYSQL_FIRST** @return*/List<UserVO> findFirstData();/*** 查询数据-MYSQL_SECOND** @return*/List<UserVO> findSecondData();}

    * Service.Impl

package com.gupao.springboot.datasourceprop.service.impl;import com.gupao.springboot.datasourceprop.mapper.first.FirstDataSourceMapper;
import com.gupao.springboot.datasourceprop.mapper.second.SecondDataSourceMapper;
import com.gupao.springboot.datasourceprop.service.IDataSourcePropService;
import com.gupao.springboot.entitys.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** @author pj_zhang* @create 2018-12-28 10:43**/
@Slf4j
@Service
public class DataSourcePropService implements IDataSourcePropService {/*** 注入first mapper层, 连接MYSQL_FIRST数据库操作*/@Autowiredprivate FirstDataSourceMapper firstDataSourceMapper;/*** 注入second mapper层, 连接MYSQL_SECOND数据库操作*/@Autowiredprivate SecondDataSourceMapper secondDataSourceMapper;@Overridepublic Integer insertFirstUserLst(UserVO userVO) {return firstDataSourceMapper.insertFirstUser(userVO);}@Overridepublic Integer insertSecondUserLst(UserVO userVO) {return secondDataSourceMapper.insertSecondUser(userVO);}@Overridepublic List<UserVO> findFirstData() {return firstDataSourceMapper.findFirstData();}@Overridepublic List<UserVO> findSecondData() {return secondDataSourceMapper.findSecondData();}}

6,Mapper层

    * Mapper层结构;其中first包对应MYSQL_FIRST数据源,second包对应MYSQL_SECOND数据源;xml文件对应结构一致,在application,properties已经指定,注意包结构用"."隔开,尝试过"/"没成功。

    * MYSQL_FIRST对应数据层

package com.gupao.springboot.datasourceprop.mapper.first;import com.gupao.springboot.entitys.UserVO;import java.util.List;/*** @author pj_zhang* @create 2018-12-28 10:43**/
public interface FirstDataSourceMapper {Integer insertFirstUser(UserVO userVO);List<UserVO> findFirstData();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.gupao.springboot.datasourceprop.mapper.first.FirstDataSourceMapper"><insert id="insertFirstUser" parameterType="com.gupao.springboot.entitys.UserVO">INSERT INTOUSER_T(USER, PASSWORD)VALUES (#{userName, jdbcType=VARCHAR},#{password, jdbcType=VARCHAR})</insert><select id="findFirstData" resultType="com.gupao.springboot.entitys.UserVO">SELECTuser as userName,password as passwordfromUSER_T</select></mapper>

    * MYSQL_SECOND对应数据层

package com.gupao.springboot.datasourceprop.mapper.second;import com.gupao.springboot.entitys.UserVO;import java.util.List;/*** @author pj_zhang* @create 2018-12-28 10:43**/
public interface SecondDataSourceMapper {Integer insertSecondUser(UserVO userVO);List<UserVO> findSecondData();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.gupao.springboot.datasourceprop.mapper.second.SecondDataSourceMapper"><insert id="insertSecondUser" parameterType="com.gupao.springboot.entitys.UserVO">INSERT INTOUSER_T(USER, PASSWORD)VALUES (#{userName, jdbcType=VARCHAR},#{password, jdbcType=VARCHAR})</insert><select id="findSecondData" resultType="com.gupao.springboot.entitys.UserVO">SELECTuser as userName,password as passwordfromUSER_T</select></mapper>

7,SpringBoot启动文件

package com.gupao.springboot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class GupaoSpringbootApplication {public static void main(String[] args) {SpringApplication.run(GupaoSpringbootApplication.class, args);}}

8,测试

    * MYSQL_FIRST入库

    * MYSQL_SECOND入库

    * MYSQL_FIRST查询

    * MYSQL_SECOND查询

    * MYSQL_FIRST数据库

    * MYSQL_SECOND数据库

这篇关于SpringBoot:多数据源配置——基于拆包配置的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1079996

相关文章

Java编译生成多个.class文件的原理和作用

《Java编译生成多个.class文件的原理和作用》作为一名经验丰富的开发者,在Java项目中执行编译后,可能会发现一个.java源文件有时会产生多个.class文件,从技术实现层面详细剖析这一现象... 目录一、内部类机制与.class文件生成成员内部类(常规内部类)局部内部类(方法内部类)匿名内部类二、

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

Springboot @Autowired和@Resource的区别解析

《Springboot@Autowired和@Resource的区别解析》@Resource是JDK提供的注解,只是Spring在实现上提供了这个注解的功能支持,本文给大家介绍Springboot@... 目录【一】定义【1】@Autowired【2】@Resource【二】区别【1】包含的属性不同【2】@

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

Java枚举类实现Key-Value映射的多种实现方式

《Java枚举类实现Key-Value映射的多种实现方式》在Java开发中,枚举(Enum)是一种特殊的类,本文将详细介绍Java枚举类实现key-value映射的多种方式,有需要的小伙伴可以根据需要... 目录前言一、基础实现方式1.1 为枚举添加属性和构造方法二、http://www.cppcns.co

Elasticsearch 在 Java 中的使用教程

《Elasticsearch在Java中的使用教程》Elasticsearch是一个分布式搜索和分析引擎,基于ApacheLucene构建,能够实现实时数据的存储、搜索、和分析,它广泛应用于全文... 目录1. Elasticsearch 简介2. 环境准备2.1 安装 Elasticsearch2.2 J

Java中的String.valueOf()和toString()方法区别小结

《Java中的String.valueOf()和toString()方法区别小结》字符串操作是开发者日常编程任务中不可或缺的一部分,转换为字符串是一种常见需求,其中最常见的就是String.value... 目录String.valueOf()方法方法定义方法实现使用示例使用场景toString()方法方法

Java中List的contains()方法的使用小结

《Java中List的contains()方法的使用小结》List的contains()方法用于检查列表中是否包含指定的元素,借助equals()方法进行判断,下面就来介绍Java中List的c... 目录详细展开1. 方法签名2. 工作原理3. 使用示例4. 注意事项总结结论:List 的 contain

Java实现文件图片的预览和下载功能

《Java实现文件图片的预览和下载功能》这篇文章主要为大家详细介绍了如何使用Java实现文件图片的预览和下载功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... Java实现文件(图片)的预览和下载 @ApiOperation("访问文件") @GetMapping("

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis