千家信息网

springboot中如何利用mybatis+druid配置动态数据源

发表于:2025-11-15 作者:千家信息网编辑
千家信息网最后更新 2025年11月15日,这篇"springboot中如何利用mybatis+druid配置动态数据源"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文
千家信息网最后更新 2025年11月15日springboot中如何利用mybatis+druid配置动态数据源

这篇"springboot中如何利用mybatis+druid配置动态数据源"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇"springboot中如何利用mybatis+druid配置动态数据源"文章吧。

一、建数据库和表
1.数据库demo1放一张user表

SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for user-- ----------------------------DROP TABLE IF EXISTS `user`;CREATE TABLE `user` (`id` int(11) NOT NULL,`name` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of user-- ----------------------------INSERT INTO `user` VALUES ('1', 'aa');INSERT INTO `user` VALUES ('2', 'bb');

2.数据库demo2放一张role表

SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for role-- ----------------------------DROP TABLE IF EXISTS `role`;CREATE TABLE `role` (`id` int(11) NOT NULL,`name` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of role-- ----------------------------INSERT INTO `role` VALUES ('1', 'CC');INSERT INTO `role` VALUES ('2', 'DD');

二、pom.xml引入包

org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-testtestorg.springframework.bootspring-boot-starter-thymeleafmysqlmysql-connector-javaruntimemysqlmysql-connector-javaorg.springframework.bootspring-boot-starter-jdbcorg.mybatis.spring.bootmybatis-spring-boot-starter2.0.1org.aspectjaspectjweavercom.alibabadruid-spring-boot-starter1.1.10com.typesafe.dynamicdatasourcedynamic-data-source_2.11

三、用generator插件生成user、role两张表的实体类、mapper.java、mapper.xml

User.javaRole.javaUserMapper.javaRoleMapper.javaUserMapper.xmlRoleMapper.xml

四、配置application.yml

server:port: 8088mybatis:mapper-locations: classpath:mapper/*.xmlspring:datasource:db1:url: jdbc:mysql://localhost:3306/demo1?useUnicode=true&characterEncoding=utf8&serverTimezone=GMTusername: rootpassword: roottype: com.alibaba.druid.pool.DruidDataSource#驱动包driver-class-name: com.mysql.cj.jdbc.Driver#初始连接数initial-size: 5#最小空闲数min-idle: 5#最大活动数max-active: 20#等待超时时间max-wait: 60000#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒time-between-eviction-runs-millis: 60000# 配置一个连接在池中最小生存的时间,单位是毫秒min-evictable-idle-time-millis: 300000#验证数据库连接的查询语句,MYSQL是select 1validation-query: SELECT 1 FROM DUAL#空闲时测试,testOnBorrow和testOnReturn在生产环境一般是不开启的,主要是性能考虑。失效连接主要通过testWhileIdle保证test-while-idle: truetest-on-borrow: falsetest-on-return: false#打开PSCache,并指定每个链接上的PSCache大小pool-prepared-statements: truemax-pool-prepared-statement-per-connection-size: 20#配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙,此处是filter修改的地方filters: stat,wall#通过connectproperties属性来打开mergesql功能:慢sql记录connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000#合并多个DruidDataSourceuseGlobalDataSourceStat: truedb2:url: jdbc:mysql://localhost:3306/demo2?useUnicode=true&characterEncoding=utf8&serverTimezone=GMTusername: rootpassword: roottype: com.alibaba.druid.pool.DruidDataSource#驱动包driver-class-name: com.mysql.cj.jdbc.Driver#初始连接数initial-size: 5#最小空闲数min-idle: 5#最大活动数max-active: 20#等待超时时间max-wait: 60000#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒time-between-eviction-runs-millis: 60000# 配置一个连接在池中最小生存的时间,单位是毫秒min-evictable-idle-time-millis: 300000#验证数据库连接的查询语句,MYSQL是select 1validation-query: SELECT 1 FROM DUAL#空闲时测试,testOnBorrow和testOnReturn在生产环境一般是不开启的,主要是性能考虑。失效连接主要通过testWhileIdle保证test-while-idle: truetest-on-borrow: falsetest-on-return: false#打开PSCache,并指定每个链接上的PSCache大小pool-prepared-statements: truemax-pool-prepared-statement-per-connection-size: 20#配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙,此处是filter修改的地方filters: stat,wall#通过connectproperties属性来打开mergesql功能:慢sql记录connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000#合并多个DruidDataSourceuseGlobalDataSourceStat: true

五、启动类扫描mapper.java文件

@SpringBootApplication@MapperScan("com.example.demo.dao")public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}

六、定义DataSourceConfig, 将application.yml中的配置导入DataSource中,并注入到bean

@Configurationpublic class DataSourceConfig {//从配置文件配置数据源@Primary@Bean(name="datasource1")@ConfigurationProperties("spring.datasource.db1")public DataSource dataSource1(){return new DruidDataSource();}//从配置文件配置数据源@Bean(name="datasource2")@ConfigurationProperties("spring.datasource.db2")public DataSource dataSource2(){return new DruidDataSource();}//动态数据源 进行数据源切换@Bean(name="dynamicDataSource")public DataSource dynamicDataSource(){DynamicDataSource dynamicDatasource=new DynamicDataSource();//设置默认数据源dynamicDatasource.setDefaultTargetDataSource(dataSource1());//配置多数据源Map dsMap=new HashMap<>();dsMap.put("datasource1",dataSource1());dsMap.put("datasource2",dataSource2());//将多数据源放到数据源池中dynamicDatasource.setTargetDataSources(dsMap);return dynamicDatasource;}}

七、定义动态数据源切换类DynamicDataSourceContextHolder

public class DynamicDataSourceContextHolder {private static final ThreadLocal contextHolder=new ThreadLocal<>();//设置数据源名称public static void setDB(String dbType){contextHolder.set(dbType);}//获取数据源名称public static String getDB(){return contextHolder.get();}//清除数据源名public static void clearDB(){contextHolder.remove();}}

八、定义获取动态数据源类DynamicDataSource

public class DynamicDataSource extends AbstractRoutingDataSource {@Overrideprotected Object determineCurrentLookupKey() {return DynamicDataSourceContextHolder.getDB();}}

九、定义mybatis配置类,将DynamicDataSource放入SqlSessionFactoryBean中

@EnableTransactionManagement@Configurationpublic class MyBatisConfig {@Resource(name = "dynamicDataSource")private DataSource dynamicDataSource;@Beanpublic SqlSessionFactory sqlSessionFactory() throws Exception {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dynamicDataSource);//将动态数据源bean配置到sqlsessionfactorysqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));return sqlSessionFactoryBean.getObject();}@Beanpublic PlatformTransactionManager platformTransactionManager() {return new DataSourceTransactionManager(dynamicDataSource);}}

十、定义用于切换数据源的注解TargetDataSource

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

十一、定义切面DynamicDataSourceAspect,用于拦截注解,并执行数据源切换功能

@Aspect@Componentpublic class DynamicDataSourceAspect {@Before("@annotation(targetDataSource)")public void beforeSwitchDS(JoinPoint point,TargetDataSource targetDataSource){DynamicDataSourceContextHolder.setDB(targetDataSource.value());}@After("@annotation(targetDataSource)")public void afterSwitchDS(JoinPoint point,TargetDataSource targetDataSource){DynamicDataSourceContextHolder.clearDB();}}

十二、测试类Test

@RestControllerpublic class Test {@Autowiredprivate RoleMapper roleMapper;@Autowiredprivate UserMapper userMapper;//未使用TargetDataSource注解,则使用默认数据源,即datasource1@RequestMapping("/ds1")public String selectDataSource1(){return userMapper.selectByPrimaryKey(1).toString();}//使用了注解,则数据源为注解中指定的datasource2@RequestMapping("/ds2")@TargetDataSource("datasource2")public String selectDataSource2(){return roleMapper.selectByPrimaryKey(1).toString();}}

测试

1.输入

http://localhost:8088/ds1

返回

2.输入

http://localhost:8088/ds2

返回

以上就是关于"springboot中如何利用mybatis+druid配置动态数据源"这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注行业资讯频道。

数据 数据源 配置 动态 空闲 内容 数据库 注解 最小 单位 时间 切换 检测 测试 监控 统计 功能 文件 最大 名称 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 网络安全在心中儿歌 外文数据库收录的文献类型有 c 数据库怎么用 直播软件开发财务计划怎么写 无声世界网络安全宣传 企业服务器维修站点地址 数据库管理系统解释名词 宣城点餐系统软件开发公司 数据库概念设计难点 黄山手机软件开发定制公司 服务器怎么开声音服务 华为服务器电源指示灯按钮被锁定 上海工行软件开发中心嘉定 梦想缔造网络技术工作室 安徽零酒互联网科技有限公司 网络安全进文章 能把数据直接复制到数据库吗 北京四维益友软件开发的系统 江西现代软件开发价格表 金山区特殊软件开发技术指导 逆战单个诸神服务器 永兴学计算机软件开发待遇 小火箭服务器节点购买要多少 交通网络安全知识考试答案 达梦数据库怎么起服务 网络安全 李雄 北京 引进学术数据库建设 重庆网络安全宣传周法治 如何让服务器只链接局域网 佰万网络技术加我QQ
0