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、测试结果
表结构如下
指定数据源调用成功!