当前位置: 首页 > news >正文

Mybatis+Druid+MybatisPlus多数据源配置

Mybatis+Druid+MybatisPlus多数据源配置

平常我们使用的是 properties 或者 yaml 来配置数据库的地址、用户名、密码等

但是这样只能配置一个数据源

现在我们想在一个项目里面配置多个数据源,那么我们就需要配置自己的配置类

配置类和配置文件

Mybatis+mysql+druid配置

spring:autoconfigure:## 多数据源环境下必须排除掉 DataSourceAutoConfiguration,否则会导致循环依赖报错exclude:- org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfigurationdatasource:# 使用druid连接池type: com.alibaba.druid.pool.DruidDataSourcedruid:#    打开我们的内置监控页面,打开后我们才可以有相应的web界面stat-view-servlet:enabled: trueurl-pattern: /druid/*login-username: userlogin-password: 123456jdbc:# 数据库链接放在外面 方便连接配置中心 做到测试和生产不同环境one:url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=true&allowMultiQueries=trueuser: rootpwd: 123456driver: com.mysql.cj.jdbc.Drivertwo:url: jdbc:mysql://ip地址:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=true&allowMultiQueries=trueuser: rootpwd: 123456driver: com.mysql.cj.jdbc.Driver# 配置自己去搜一下吧 这里我没有配置完datasource:# druid 配置druid:#        打开我们的内置监控功能,打开之后我们才可以对我们的操作进行统计filter:stat:enabled: trueslow-sql-millis: 2000#      配置防火墙,防止sql语句注入,我们可以设置我们想要那些语句可以执行,哪些不行wall:enabled: trueconfig:delete-allow: true#            select-all-column-allow: false,如果我们设置了拒绝查询,那么我们查询时就会报错,返回一个whitePage#            selelct-allow: false#        打开我们的Web关联监控配置,即我们对某些路径进行精确统计web-stat-filter:enabled: true# 初始化时建立的物理连接数。初始化发生在显式调用init方法,或者第一次getConnection时.initial-size: 5# 连接池最大物理连接数量。max-active: 50# 连接池最小物理连接数量。min-idle: 5# 获取连接时最大等待时间,单位为毫秒。# 配置之后,缺省启用公平锁,并发效率会有所下降,若需要可以通过配置useUnfairLock属性为true使用非公平锁。max-wait: 6000# 是否缓存preparedStatement,也就是PSCache。# PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。pool-prepared-statements: true# 要启用PSCache,其值必须大于0,当大于0时,poolPreparedStatements自动触发修改为true。# 在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100。max-pool-prepared-statement-per-connection-size: 20# 用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。# 如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。validation-query: select 1 from dual# 检测连接是否有效的超时时间,单位为秒。# 底层调用jdbc Statement对象的void setQueryTimeout(int seconds)方法。#      validation-query-timeout: 30# 有两个含义:#  1) Destroy线程会检测连接的间隔时间,若连接空闲时间大于等于minEvictableIdleTimeMillis则关闭物理连接。#  2) testWhileIdle的判断依据,详细看testWhileIdle属性的说明。time-between-eviction-runs-millis: 60000# 连接保持空闲而不被驱逐的最长时间。min-evictable-idle-time-millis: 300000# 建议配置为true,不影响性能,并且保证安全性。# 申请连接的时候检测,若空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。test-while-idle: true# 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。test-on-borrow: false# 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。test-on-return: false# 类型是字符串,通过别名的方式配置扩展的拦截器插件,常用的拦截器插件有:# 监控统计用的filter:stat,日志用的filter:log4j,防御sql注入攻击的filter:wall,三个同时配置的化,用逗号隔开。# 注意,Druid中的filter-class-names配置项是不起作用的,必须采用filters配置项才可以。filters: stat,wall,log4j2# 通过connectProperties属性来打开mergeSql功能;慢SQL记录。connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000# 合并多个DruidDataSource的监控数据use-global-data-source-stat: truemybatis-plus:configuration:# 更新字段的时候设置为null,忽略实体null判断之后,解决Oracle无效的列异常, oracle数据库必须配置jdbc-type-for-null: 'null'  # 注意要有单引号# mybatis-plus驼峰映射map-underscore-to-camel-case: true# 这个配置会将执行的sql打印出来,在开发或测试的时候可以用log-impl: org.apache.ibatis.logging.stdout.StdOutImpl# mybatis的xml文件地址,如果启动文件找不到xml文件,如下去修改pom.xml文件mapper-locations: classpath:mybatis/two/*.xmlglobal-config:# 禁用mybatis-plus的LOGObanner: falsedb-config:# 逻辑未删除值,(逻辑删除下有效)logic-delete-value: 1# 逻辑未删除值,(逻辑删除下有效)需要注入逻辑策略LogicSqlInjector,以@Bean方式注入logic-not-delete-value: 0# 对应实体类的字段,写了这个在实体类中就不需要写注解了logic-delete-field: deleted

项目的配置项文件:

在这里插入图片描述

配置项:Druid配置

package com.example.test.config;import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;import java.sql.SQLException;@Data
@ConfigurationProperties(prefix = "jdbc.datasource.druid")
public class DruidConfig {protected String filters;protected int initialSize;protected int minIdle;protected int maxActive;protected long maxWait;protected long timeBetweenEvictionRunsMillis;protected long minEvictableIdleTimeMillis;protected String validationQuery;protected boolean testWhileIdle;protected boolean testOnBorrow;protected boolean testOnReturn;protected boolean poolPreparedStatements;protected int maxPoolPreparedStatementPerConnectionSize;/*** 初始化* @return* @throws SQLException*/protected DruidDataSource init() throws SQLException {DruidDataSource druid = new DruidDataSource();// 监控统计拦截的filtersdruid.setFilters(filters);//初始化时建立物理连接的个数druid.setInitialSize(initialSize);//最大连接池数量druid.setMaxActive(maxActive);//最小连接池数量druid.setMinIdle(minIdle);//获取连接时最大等待时间,单位毫秒。druid.setMaxWait(maxWait);//间隔多久进行一次检测,检测需要关闭的空闲连接druid.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);//一个连接在池中最小生存的时间druid.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);//用来检测连接是否有效的sqldruid.setValidationQuery(validationQuery);//建议配置为true,不影响性能,并且保证安全性。druid.setTestWhileIdle(testWhileIdle);//申请连接时执行validationQuery检测连接是否有效druid.setTestOnBorrow(testOnBorrow);druid.setTestOnReturn(testOnReturn);//是否缓存preparedStatement,也就是PSCache,oracle设为true,mysql设为false。分库分表较多推荐设置为falsedruid.setPoolPreparedStatements(poolPreparedStatements);// 打开PSCache时,指定每个连接上PSCache的大小druid.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);return druid;}
}

配置项:数据源一

package com.example.test.config;import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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;
import java.sql.SQLException;/*** 双数据库配置 因为一部分查询需要用到* oneDataSource -》 数据库一* twoDataSource -》 数据库二*/
@Configuration
@MapperScan(basePackages = OneDBConfig.PACKAGE, sqlSessionFactoryRef = "oneSqlSessionFactory")
public class OneDBConfig extends DruidConfig {/*** dao层的包路径*/static final String PACKAGE = "com.example.test.mapper.one";/*** mapper文件的相对路径*/private static final String MAPPER_LOCATION = "classpath*:mybatis/one/*.xml";@Value("${jdbc.one.url}")private String url;@Value("${jdbc.one.user}")private String user;@Value("${jdbc.one.pwd}")private String pwd;@Value("${jdbc.one.driver}")private String driverName;@Bean(name = "oneDataSource")public DataSource oneDataSource() throws SQLException {DruidDataSource druid = init();// 配置基本属性druid.setDriverClassName(driverName);druid.setUsername(user);druid.setPassword(pwd);druid.setUrl(url);return druid;}@Bean(name = "oneSqlSessionFactory")public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));return bean.getObject();}@Bean(name = "oneTransactionManager")public DataSourceTransactionManager secondaryTransactionManager(@Qualifier("oneDataSource") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}}

配置项:数据源二 ,该数据源作为MybatisPlus的使用数据源

package com.example.test.config;import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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;
import org.springframework.util.StringUtils;import javax.sql.DataSource;
import java.sql.SQLException;/*** 双数据库配置 因为一部分查询需要用到* 该 数据库配资源 作为 mybatisPlus 的使用源* oneDataSource -》 数据库一* twoDataSource -》 数据库二*/
@Configuration
@EnableConfigurationProperties({MybatisPlusProperties.class})
@MapperScan(basePackages = TwoDBConfig.PACKAGE, sqlSessionFactoryRef = "twoSqlSessionFactory")
public class TwoDBConfig extends DruidConfig {private final MybatisPlusProperties properties;/*** dao层的包路径*/static final String PACKAGE = "com.example.test.mapper.two";/*** mapper文件的相对路径*/private static final String MAPPER_LOCATION = "classpath*:mybatis/two/*.xml";@Value("${jdbc.two.url}")private String url;@Value("${jdbc.two.user}")private String user;@Value("${jdbc.two.pwd}")private String pwd;@Value("${jdbc.two.driver}")private String driverName;public TwoDBConfig(MybatisPlusProperties properties) {this.properties = properties;}@Bean(name = "twoDataSource")@Primarypublic DataSource dataSource() throws SQLException {DruidDataSource druid = init();// 配置基本属性druid.setDriverClassName(driverName);druid.setUsername(user);druid.setPassword(pwd);druid.setUrl(url);return druid;}@Bean(name = "twoSqlSessionFactory")@Primarypublic SqlSessionFactory twoSqlSessionFactory(@Qualifier("twoDataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));MybatisConfiguration configuration = this.properties.getConfiguration();if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) {configuration = new MybatisConfiguration();}bean.setConfiguration(configuration);return bean.getObject();}@Primary@Bean(name = "twoTransactionManager")public DataSourceTransactionManager twoTransactionManager(@Qualifier("twoDataSource") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}
}

MybatisPlus插件

/*** MybatisPlus 配置类*/
@EnableTransactionManagement //事务控制
@Configuration //配置类
public class MyBatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();//分页插件interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}
}

Mapper路径

在这里插入图片描述

XML路径

在这里插入图片描述

测试:

controller

@RestController
@Slf4j
@RequestMapping("/cs")
public class TestController {@Autowiredprivate OneMapper oneMapper;@Autowiredprivate TwoMapper twoMapper;@PostMapping("/test")public Results test() {int count1 = oneMapper.count();int count2 = twoMapper.count();log.info("数据源一:{},数据源二:{}", count1, count2);return Results.success(count1 + "+" + count2);}
}

postman:

在这里插入图片描述

Druid页面:

在这里插入图片描述


http://www.mrgr.cn/news/29540.html

相关文章:

  • 高效音频格式转换实战:使用Python和FFmpeg处理MP3到WAV的转换20240918
  • 启程Pulsar:深入剖析高速启动引擎,揭秘消息中间件巨兽的诞生
  • Matlab 的.m 文件批量转成py文件
  • Vue|mixin混入
  • YOLOv8 OBB win10+ visual 2022移植部署
  • 如何使用宝塔面板安装中间件
  • Fastdds_ContentFilteredTopicExample_代码剖析5_create_publisher
  • 【C++】多态的认识和理解
  • Java 中的 sleep、wait、join 怎么理解
  • Verdin AM62 引脚复用配置
  • 【MySQL】MySQL连接池原理与简易网站数据流动是如何进行
  • yaml注入配置文件
  • IEEE-754 32位十六进制数 转换为十进制浮点数
  • 游戏开发应具备的心理学知识
  • 【Python机器学习】NLP信息提取——正则模式
  • Kubernetes从零到精通(12-Ingress、Gateway API)
  • Sqlmap中文使用手册 - File system access模块参数使用
  • 米壳AI:跨境电商必备:不损失原图的图片翻译工具!
  • 感谢问界M9一打二十,让我们买到这么便宜的BBA
  • element-ui 日期选择器设置禁用日期