一、除了MySQL驱动,我们还需要用到postgresql的驱动,所以我们先把驱动的依赖给导入进来
org.postgresql
postgresql
二,修改application-druid.yml:
# 数据源配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 主库数据源
master:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/i_ren_shi?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: root
# 从库数据源
slave:
# 从数据源开关/默认关闭
enabled: true
driverClassName: org.postgresql.Driver
url: jdbc:postgresql://localhost:5432/easytrack
username: 123456
password: 123456
easytrack:
# 从数据源开关/默认关闭
enabled: true
driverClassName: org.postgresql.Driver
url: jdbc:postgresql://localhost:5432/easytrack
username: 123456
password: 123456
三、新数据源的配置
(1)修改DatasourceType
package com.ruoyi.common.enums;
/**
* 数据源
*
* @author ruoyi
*/
public enum DataSourceType
{
/**
* 主库
*/
MASTER,
/**
* 从库
*/
SLAVE,
/**
* 新配置数据源名称
*/
EASYTRACK
}
(2)修改DruidConfig,这里有很多细节要注意,就是大小写的问题
@Bean
@ConfigurationProperties("spring.datasource.druid.easytrack")
@ConditionalOnProperty(prefix = "spring.datasource.druid.easytrack", name = "enabled", havingValue = "true")
public DataSource easyTrackDataSource(DruidProperties druidProperties)
{
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean(name = "dynamicDataSource")
@Primary
public DynamicDataSource dataSource(DataSource masterDataSource)
{
Map
(3)使用选择数据源,会自动切换数据源
@DataSource(value = DataSourceType.EASYTRACK)