SpringBoot+MybatisPlus+jdbc連接池配置多數(shù)據(jù)源的實(shí)現(xiàn)
上pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-dataSource</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-dataSource</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR5</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.1.8</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
目錄結(jié)構(gòu)

application.xml的結(jié)構(gòu)
server:
port: 9086
spring:
datasource: #database
primary: # 3.0 Datasource
jdbc-url: jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&autoReconnect=true&zeroDateTimeBehavior=convertToNull
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
secondary: # 2.0 Datasource
jdbc-url: jdbc:mysql://localhost:3306/user02?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&autoReconnect=true&zeroDateTimeBehavior=convertToNull
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
application:
name: lixiaolong
#mybatis
mybatis-plus:
mapper-locations: classpath:/mapper/*Mapper.xml
#實(shí)體掃描,多個(gè)package用逗號(hào)或者分號(hào)分隔
typeAliasesPackage: com.example.demo.entity;
global-config:
#主鍵類型 0:"數(shù)據(jù)庫(kù)ID自增", 1:"用戶輸入ID",2:"全局唯一ID (數(shù)字類型唯一ID)", 3:"全局唯一ID UUID";
id-type: 0
#字段策略 0:"忽略判斷",1:"非 NULL 判斷"),2:"非空判斷"
field-strategy: 2
#駝峰下劃線轉(zhuǎn)換
db-column-underline: true
#刷新mapper 調(diào)試神器
refresh-mapper: true
#數(shù)據(jù)庫(kù)大寫下劃線轉(zhuǎn)換
#capital-mode: true
logic-delete-value: -1
logic-not-delete-value: 0
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
重要組成部分
1.數(shù)據(jù)源注解以及aop配置
一.
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
DataSourceEnum value() default DataSourceEnum.DB1;
}
二.
@Component
@Slf4j
@Aspect
@Order(-1)
public class DataSourceAspect {
@Pointcut("@within(com.example.demo.annotation.DataSource) || @annotation(com.example.demo.annotation.DataSource)")
public void pointCut(){
}
@Before("pointCut() && @annotation(dataSource)")
public void doBefore(DataSource dataSource){
// log.info("選擇數(shù)據(jù)源---"+dataSource.value().getValue());
DataSourceContextHolder.setDataSource(dataSource.value().getValue());
}
@After("pointCut()")
public void doAfter(){
DataSourceContextHolder.clear();
}
}
mybatisplus動(dòng)態(tài)數(shù)據(jù)源的配置
一.mybatisplus動(dòng)態(tài)數(shù)據(jù)源配置類
@Configuration // 注解到spring容器中
@MapperScan(basePackages = "com.example.demo.mapper*")
public class MybatisDataSource {
/*
* 分頁(yè)插件,自動(dòng)識(shí)別數(shù)據(jù)庫(kù)類型 多租戶,請(qǐng)參考官網(wǎng)【插件擴(kuò)展】
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 開啟 PageHelper 的支持
paginationInterceptor.setLocalPage(true);
return paginationInterceptor;
}
/**
* SQL執(zhí)行效率插件
*/
@Bean
@Profile({ "dev", "qa" }) // 設(shè)置 dev test 環(huán)境開啟
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(1000);
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
/**
* 返回data1數(shù)據(jù)庫(kù)的數(shù)據(jù)源
*
* @return
*/
@Bean(name = "primary")
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primary() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondary")
// @Primary//主數(shù)據(jù)源
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondary() {
return DataSourceBuilder.create().build();
}
@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(multipleDataSource(primary(), secondary()));
// sqlSessionFactory.setMapperLocations(new
// PathMatchingResourcePatternResolver().getResources("classpath:/mapper/*/*Mapper.xml"));
MybatisConfiguration configuration = new MybatisConfiguration();
// configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
configuration.setJdbcTypeForNull(JdbcType.NULL);
configuration.setMapUnderscoreToCamelCase(true);
configuration.setCacheEnabled(false);
sqlSessionFactory.setConfiguration(configuration);
sqlSessionFactory.setPlugins(new Interceptor[] { // PerformanceInterceptor(),OptimisticLockerInterceptor()
paginationInterceptor() // 添加分頁(yè)功能
});
// sqlSessionFactory.setGlobalConfig(globalConfiguration());
return sqlSessionFactory.getObject();
}
/**
* 動(dòng)態(tài)數(shù)據(jù)源配置
*
* @return
*/
@Bean
@Primary
public DataSource multipleDataSource(@Qualifier("primary") DataSource db1,
@Qualifier("secondary") DataSource db2) {
MultipleDataSource multipleDataSource = new MultipleDataSource();
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceEnum.DB1.getValue(), db1);
targetDataSources.put(DataSourceEnum.DB2.getValue(), db2);
// 添加數(shù)據(jù)源
multipleDataSource.setTargetDataSources(targetDataSources);
// 設(shè)置默認(rèn)數(shù)據(jù)源
multipleDataSource.setDefaultTargetDataSource(db1);
return multipleDataSource;
}
}
二.配置其他
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new InheritableThreadLocal<>();
/**
* 設(shè)置數(shù)據(jù)源
* @param db
*/
public static void setDataSource(String db){
contextHolder.set(db);
}
/**
* 取得當(dāng)前數(shù)據(jù)源
* @return
*/
public static String getDataSource(){
return contextHolder.get();
}
/**
* 清除上下文數(shù)據(jù)
*/
public static void clear(){
contextHolder.remove();
}
}
三.
public class MultipleDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
// TODO Auto-generated method stub
return DataSourceContextHolder.getDataSource();
}
}
測(cè)試是否成功
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("dev")
public class SpringDataSourceApplicationTests {
@Autowired
private UserMapper userService;
@Autowired
private User02Service user02Service;
@Test
public void contextLoads() {
User user = userService.selectById(1);
User02 user02 = new User02();
BeanUtils.copyProperties(user, user02);
user02Service.insert(user02);
System.out.printf("數(shù)據(jù)是:");
}
}
測(cè)試結(jié)果

到此這篇關(guān)于SpringBoot+MybatisPlus+jdbc連接池配置多數(shù)據(jù)源的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot MybatisPlus jdbc多數(shù)據(jù)源內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- spring boot使用sharding jdbc的配置方式
- 詳解springboot采用多數(shù)據(jù)源對(duì)JdbcTemplate配置的方法
- springboot2.0.0配置多數(shù)據(jù)源出現(xiàn)jdbcUrl is required with driverClassName的錯(cuò)誤
- SpringBoot多數(shù)據(jù)源配置詳細(xì)教程(JdbcTemplate、mybatis)
- 詳解Springboot之整合JDBCTemplate配置多數(shù)據(jù)源
- springboot+springJdbc+postgresql 實(shí)現(xiàn)多數(shù)據(jù)源的配置
- springboot實(shí)現(xiàn)以代碼的方式配置sharding-jdbc水平分表
- SpringBoot3+ShardingJDBC5.5.0 讀寫分離配置的實(shí)現(xiàn)
- SpringBoot?配置多個(gè)JdbcTemplate的實(shí)現(xiàn)步驟
- Spring?JDBC配置與使用的實(shí)現(xiàn)
相關(guān)文章
學(xué)會(huì)在Java中使用Optional功能
這篇文章主要介紹了學(xué)會(huì)在Java中使用Optional功能,在本文中,我們將了解如何、何時(shí)以及在哪里最好地應(yīng)用Optional,具體相關(guān)內(nèi)容需要的朋友可以參考下面文章內(nèi)容2022-09-09
Java兩大工具庫(kù)Commons和Guava使用示例詳解
這篇文章主要為大家介紹了Java兩大工具庫(kù)Commons和Guava使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
SpringBoot啟動(dòng)時(shí)如何通過啟動(dòng)參數(shù)指定logback的位置
這篇文章主要介紹了SpringBoot啟動(dòng)時(shí)如何通過啟動(dòng)參數(shù)指定logback的位置,在spring boot中,使用logback配置的方式常用的有兩種,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-07-07
IDEA中Directory創(chuàng)建多級(jí)目錄的實(shí)現(xiàn)
本文主要介紹了IDEA中Directory創(chuàng)建多級(jí)目錄的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06

