最新版本的springboot连接两个数据源
搭建是springboot项目
多数据源是是我们在项目中经常可能用到的,可能是主从模式、可能是其他项目相关的库。
我这里仅仅是将spring-boot作为单体应用,采用分布式方式,并非微服务。进入正题:
一、springboot的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.3.2.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.peakcloud.first</groupId>
<artifactId>em</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>em</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<org.mybatis.version>3.5.1</org.mybatis.version>
<tk.mybatis.version>4.1.5</tk.mybatis.version>
<tk.mybatis.boot.version>2.0.4</tk.mybatis.boot.version>
<mybatis-spring-boot-starter.version>1.1.1</mybatis-spring-boot-starter.version>
<mybatis-pagehelper.version>5.1.10</mybatis-pagehelper.version>
<!-- JApidocs接口包 -->
<japidocs-version>1.4.1</japidocs-version>
<!-- 生成表结构等等 -->
<mybatis.generator.version>1.3.7</mybatis.generator.version>
<mysql-connector-java.version>8.0.21</mysql-connector-java.version>
</properties>
<dependencies>
<!-- spring-boot启动 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JAPIdocs 接口文档 -->
<dependency>
<groupId>io.github.yedaxia</groupId>
<artifactId>japidocs</artifactId>
<version>${japidocs-version}</version>
</dependency>
<!-- lombok 工具 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 采用切面进行数据库连接 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<!-- Druid 数据连接池依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
<!-- 分页工具包 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${mybatis-pagehelper.version}</version>
</dependency>
<!-- ====================================================================================== -->
<!-- mysql数据连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- tk mybatis引入使用 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>${tk.mybatis.version}</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>${tk.mybatis.boot.version}</version>
</dependency>
<!-- mybatis引入使用 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${org.mybatis.version}</version>
</dependency>
<!-- mybatis整合报错解决方案 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring-boot-starter.version}</version>
</dependency>
<!-- MyBatis Generator 插件:核心包 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>${mybatis.generator.version}</version>
</dependency>
<!-- ====================================================================================== -->
<!-- mongo -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- ====================================================================================== -->
<!-- redis连接池(限流) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 启动项目报错reids问题 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!--JWT java web token 权限验证-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
<!--shiro 权限框架-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<!--阿里json转换-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
</dependencies>
<!-- mavend打jar包 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- MyBatis Generator 插件:数据库表对应 POJO 生成工具。 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>${mybatis.generator.version}</version>
<configuration>
<configurationFile>src/main/resources/generator.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.1.5</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>${mybatis.generator.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator</artifactId>
<version>${mybatis.generator.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>${mybatis.generator.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
二、进行application.yml配置
server:
port: 8080
servlet:
context-path: /em
spring:
datasource:
druid:
em:
#配置监控统计拦截的filters,去掉后监控界面SQL无法进行统计,'wall'用于防火墙
filters: stat,wall
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/em?characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai
username: root
password: 123456
#初始化大小
initial-size: 1
#最小连接数
min-idle: 1
#最大连接数
max-active: 20
#获取连接等待超时时间
max-wait: 60000
#间隔多久才进行一次检测,检测需要关闭的空闲连接,单位毫秒
time-between-eviction-runs-millis: 60000
#一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 30000
#测试语句是否执行正确
validation-query: SELECT 'x'
#指明连接是否被空闲连接回收器(如果有)进行检验.如果检测失败,则连接将被从池中去除.
test-while-idle: true
#借出连接时不要测试,否则很影响性能
test-on-borrow: false
test-on-return: false
#打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
pool-prepared-statements: false
#与Oracle数据库PSCache有关,再druid下可以设置的比较高
max-pool-prepared-statement-per-connection-size: 20
act:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/act?characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai
username: root
password: 123456
initial-size: 1
min-idle: 1
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 30000
validation-query: SELECT 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: false
max-pool-prepared-statement-per-connection-size: 20
# mongoDB 链接
data:
mongodb:
uri: mongodb://em:123456@127.0.0.1:27027/em
redis:
database: 0
host: 127.0.0.1
port: 6379
timeout: 5000
lettuce:
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
#这是解决启动报错无法加载redis重名问题
main:
allow-bean-definition-overriding: true #当遇到同样名字的时候,是否允许覆盖注册
#LogBack-Boot配置
logging:
config: classpath:logback-spring.xml
# 日志目录
logger_home: ../logs/em
# 源码根目录
root_dir: com.peakcloud.first.em
三、添加Druid监控配置
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Auther: java-cj
* @describtion: Druid监控配置
*/
@Configuration
public class DruidConfig {
/**
* 注入servlet信息,配置监控图
*
*/
@Bean
@ConditionalOnMissingBean
public ServletRegistrationBean druidServlet(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
//添加可以远程访问的监控地址
servletRegistrationBean.addInitParameter("allow","127.0.0.1");
servletRegistrationBean.addInitParameter("loginUsername","admin");
servletRegistrationBean.addInitParameter("loginPassword","admin");
servletRegistrationBean.addInitParameter("resetEnable","true");
return servletRegistrationBean;
}
/**
*
* 注册filter信息,用于拦截
*/
@Bean
@ConditionalOnMissingBean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}
四、配置数据源1:
package com.peakcloud.first.em.datasource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import tk.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
@Configuration
@MapperScan(basePackages = "com.peakcloud.first.em.mvc.dao",sqlSessionTemplateRef = "emSqlSessionTemplate")
public class DataSource1Config {
@Bean(name = "emDataSource")
@ConfigurationProperties(prefix = "spring.datasource.druid.em")
@Primary
public DruidDataSource emDataSource(){
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "emSqlSessionFactory")
@Primary
public SqlSessionFactory emsqlSessionFactory(@Qualifier("emDataSource") DruidDataSource druidDataSource) throws Exception{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(druidDataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapping/*/*.xml"));
return bean.getObject();
}
@Bean(name = "emTransactionManager")
@Primary
public DataSourceTransactionManager emTransactionManager(@Qualifier("emDataSource")DruidDataSource druidDataSource){
return new DataSourceTransactionManager(druidDataSource);
}
@Bean(name = "emSqlSessionTemplate")
@Primary
public SqlSessionTemplate emSqlSessionTemplate(@Qualifier("emSqlSessionFactory")SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
}
}
五、配置数据源2:
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import tk.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
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;
@Configuration
@MapperScan(basePackages = "com.peakcloud.first.em.mvc.daoAct",sqlSessionTemplateRef = "actSqlSessionTemplate")
public class DataSource2Config {
@Bean(name = "actDataSource")
@ConfigurationProperties(prefix = "spring.datasource.druid.act")
public DruidDataSource actDataSource(){
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "actSqlSessionFactory")
public SqlSessionFactory actsqlSessionFactory(@Qualifier("actDataSource") DruidDataSource druidDataSource) throws Exception{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(druidDataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapping/*/*.xml"));
return bean.getObject();
}
@Bean(name = "actTransactionManager")
public DataSourceTransactionManager actTransactionManager(@Qualifier("actDataSource")DruidDataSource druidDataSource){
return new DataSourceTransactionManager(druidDataSource);
}
@Bean(name = "actSqlSessionTemplate")
public SqlSessionTemplate actSqlSessionTemplate(@Qualifier("actSqlSessionFactory")SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
}
}
六、项目启动添加如下:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import tk.mybatis.spring.annotation.MapperScan;
/** 去除默认的DataSourceAutoConfiguration */
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
/** 切记一定要配置两个,不然启动会出现空指针错误 */
@MapperScan({"com.peakcloud.first.em.mvc.dao.mapper","com.peakcloud.first.em.mvc.daoAct.mapper"})
/** 开启事务支持 */
@EnableTransactionManagement
public class EmApplication {
public static void main(String[] args) {
SpringApplication.run(EmApplication.class, args);
}
}