mysql-plus多数据库_Springboot+mybatisplus+mysql配置多数据源(注解版)
1、添加依賴,最關鍵的兩個依賴是后面兩個"druid依賴"和"配置動態數據源"(已標紅),其他"非主要"依賴可按自身實際開發環境進行選擇。
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-web
com.baomidou
mybatis-plus-boot-starter
3.1.1
com.baomidou
mybatis-plus-generator
3.1.1
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-thymeleaf
net.sourceforge.nekohtml
nekohtml
org.projectlombok
lombok
1.18.8
org.freemarker
freemarker
2.3.28
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.5
org.mybatis
mybatis
cn.hutool
hutool-all
5.0.7
com.alibaba
fastjson
1.2.4
com.alibaba
druid-spring-boot-starter
1.1.20
com.baomidou
dynamic-datasource-spring-boot-starter
2.5.6
2、添加數據源,在application.yml添加如下配置,其中primary: demo表示默認數據源為demo,即在不添加注解指定的情況下數據源為demo
spring:
datasource:
dynamic:
primary: demo # 配置默認數據庫
datasource:
demo: # 數據源1配置
url: jdbc:mysql://localhost:3306/demo?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
test: # 數據源2配置
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
durid:
initial-size: 1
max-active: 20
min-idle: 1
max-wait: 60000
autoconfigure:
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure # 去除druid配置
3、啟動類添加注解
在@SpringBootApplication中添加exclude = DruidDataSourceAutoConfigure.class,可取消系統自動配置數據源,這很關鍵,不要忘記!否則會報尋找不到"xxx" bean的錯誤
@MapperScan("com.xlfdy.test.mapper")
@SpringBootApplication(exclude= DruidDataSourceAutoConfigure.class)
@EnableCaching
@EnableSchedulingpublic classTestApplication {public static voidmain(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
4、功能測試
在需要切換指定數據源的方法或類上添加@DS("xxx")注解,"xxx"表示要切換的數據源名稱,當方法和類上都有該注解時,以方法上的注解為準,service和mapper、controller中都可配置該注解。
@Servicepublic class TblUserServiceImpl extends ServiceImpl implementsITblUserService {
@Override
@DS("test")publicTblUser getAllUser(Integer id) {
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.eq("id",id);
TblUser user=baseMapper.selectOne(wrapper);returnuser;
}
}
5、測試結果
表結構如下
指定數據源調用成功!
總結
以上是生活随笔為你收集整理的mysql-plus多数据库_Springboot+mybatisplus+mysql配置多数据源(注解版)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 亚马逊Rekognition发布针对人脸
- 下一篇: python自动保存图片_Python学