springboot配置多数据源@DS
1.引入多数据源maven依赖,同时记得引如对应数据源的驱动
<!--多数据源-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2.配置文件配置多个数据源
#主数据库
spring.datasource.dynamic.primary=base
spring.datasource.dynamic.datasource.base.username=root
spring.datasource.dynamic.datasource.base.password=123456
spring.datasource.dynamic.datasource.base.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.dynamic.datasource.base.url=jdbc:sqlserver://数据库ip:1433;DatabaseName=test1
spring.datasource.dynamic.datasource.his.username=root
spring.datasource.dynamic.datasource.his.password=654321
spring.datasource.dynamic.datasource.his.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.dynamic.datasource.his.url=jdbc:sqlserver://localhost:1433;DatabaseName=test2
3.1 使用方法1,在类或者方法上加注解加@DS切换数据源
@Controller
@RequestMapping("/demo")
public class DemoController {
@Resource
private ProjetcServices projectService;
@ResponseBody
@GetMapping("/get1")
public List<Map> get1(){
List<Map> list = projectService.get1();
return list;
}
@DS("his")
@ResponseBody
@GetMapping("/get2")
public List<Map> get2(){
List<Map> list = projectService.get2();
return list;}
}
3.2 使用方法2,在类或者方法上加注解加@DS切换数据源,方法上优先于类上
@DS("his")
@Service
public class ProjetcServices {
@Resource
private ProjectDao projectDao;
@DS("base")
public List<Map> get1() {
return projectDao.get1();
}
public List<Map> get2() {
return projectDao.get2();}
}