application.yml 配置文件
server:
port: 8080
spring:
datasource:
dynamic:
primary: db1 # 配置默认数据库
datasource:
db1: # 数据源1配置
url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
db2: # 数据源2配置
url: jdbc:mysql://localhost:3306/db2?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
username: root
password: root
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配置
注:
(1)低版本springboot配置数据库 url 时使用 url 属性,高版本springboot使用 jdbc-url 属性 。
(2)DruidDataSourceAutoConfigure
会注入一个DataSourceWrapper
,其会在原生的spring.datasource
下找 url, username, password 等。而动态数据源 URL 等配置是在 dynamic 下,因此需要排除,否则会报错。
排除方式有两种:
一种是上述配置文件排除:
autoconfigure:
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure # 去除druid配置
另一种可以在项目启动类排除:
@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
(3)如果需要读写分离:比如 db1 中负责增删改,db2 中负责查询,需要注意的是负责增删改的数据库必须是主库(master)
pom.xml与数据库相关依赖
- dynamic-datasource-spring-boot-starter # 配置动态数据源
- druid-spring-boot-starter # 阿里的数据库连接池
- mysql-connector-java
给使用非默认数据源添加注解@DS
@DS可以注解在方法上和类上,同时存在方法注解优先于类上注解。
注解在 service 实现或 mapper 接口方法上,不要同时在 service 和 mapper 注解。
@DS("db2")
public interface UserMapper extends BaseMapper<User> {
}
@Service
@DS("db2")
public class ModelServiceImpl extends ServiceImpl<ModelMapper, Model> implements IModelService {}
@Select("SELECT * FROM user")
@DS("db2")
List<User> selectAll();