一、需求说明
1. 项目要求同时操作两个数据库,一个在本地服务器,一个在云服务器。
2. 两个数据库均为SQL server数据库。
二、实现
1. 在pom中导入多数据源依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.6.0</version>
</dependency>
2. 在application.yml中配置数据库
spring:
datasource:
dynamic:
type: com.alibaba.druid.pool.DruidDataSource
strict: false
datasource:
master:
driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
password: password
url: jdbc:sqlserver://localhost:1433;databaseName=name;encrypt=true;trustServerCertificate=true
username: username
cloud:
driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
password: password
url: jdbc:sqlserver://ip:端口;databaseName=name;encrypt=true;trustServerCertificate=true
username: username
注意:database需要指定主数据库(默认数据库)即master,不然在项目启动时会出现警告;第二个数据库名字随意,你也可以叫cloud1、cloud2.....
3. 挂载数据库
在ServiceImpl中使用注解@DS(""),表明需要操作哪个数据库。如果没有使用@DS,spring将默认使用master数据库:
@Service("userService_C")
@DS("cloud")
public class UserServiceImpl_C implements UserService_C {
@Resource
private UserMapper userMapper;
@Override
public List<User> selectUser(String where) {
return userMapper.selectUser(where);
}
}
注意:@DS不一定要在ServiceImpl中使用,同样可以在mapper、service接口使用
4. 具体Demo
1)目录结构:
2)UserMapper:
@Mapper
public interface UserMapper {
@Select({"select * from User_loginData where 1=1 ${where}"})
List<User> selectUser(@Param("where")String where);
}
3)UserService_C && UserService_L:
public interface UserService_C {
List<User> selectUser(String where);
}
public interface UserService_L {
List<User> selectUser(String where);
}
4)UserServiceImpl_C && UserServiceImpl_C:
@Service("userService_C")
@DS("cloud")
public class UserServiceImpl_C implements UserService_C {
@Resource
private UserMapper userMapper;
@Override
public List<User> selectUser(String where) {
return userMapper.selectUser(where);
}
}
@Service("userService_L")
public class UserServiceImpl_L implements UserService_L {
@Resource
private UserMapper userMapper;
@Override
public List<User> selectUser(String where) {
return userMapper.selectUser(where);
}
}
5)UserController:
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService_L l_userService = new UserServiceImpl_L();
@Resource
private UserService_C c_userService = new UserServiceImpl_C();
@RequestMapping(value = "/userList")
public String addPre() {
String msg = "";
try {
List<User> c_users = c_userService.selectUser("and userId = 12");
List<User> l_users = l_userService.selectUser("and userId = 12");
System.out.println("云服务器最后登录时间:"+c_users.get(0).getUserLoginTime());
System.out.println("本地服务器最后登录时间:"+l_users.get(0).getUserLoginTime());
}catch (Exception e){
System.out.println(e.getMessage());
}
return msg;
}
}