添加依赖
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.18</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.3.2</version></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.6.1</version></dependency></dependencies>
application.yml配置
spring:datasource:dynamic:primary: materstrict: falsedatasource:master:username: lichaopassword: 123456driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://192.168.1.19:3306/seckill?useSSL=false&useUnicode=true&characterEncoding=utf8&allowPublicKeyRetrieval=true&autoReconnect=true&serverTimezone=Asia/Shanghaisecond:username: lichaopassword: 123456driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://192.168.1.20:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8&allowPublicKeyRetrieval=true&autoReconnect=true&serverTimezone=Asia/Shanghai
service层配置
- 共用mapper层文件
@Service
@DS("master")
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic User getUserById(Integer id) {return userMapper.selectByPrimaryKey(id);}@Override@DS("second")public User getUserByIdFromSecondDB(Integer id) {return userMapper.selectByPrimaryKey(id);}
}
测试结果
测试结果符合预期,查询的数据是根据标记的数据库获取
参考
- 多数据源支持