位置:在
pom.xml
文件中添加MySQL
和达梦
的驱动依赖
<!-- Mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 达梦驱动包 -->
<dependency>
<groupId>com.dameng</groupId>
<artifactId>Dm7JdbcDriver18</artifactId>
<version>7.6.0.165</version>
</dependency>
位置:application-druid.yml
# 数据源配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 主库数据源
master:
url: jdbc:mysql://localhost:3306/yourdb
username: yourusername
password: yourpassword
driverClassName: com.mysql.cj.jdbc.Driver
slave:
# 从数据源开关/默认关闭
enabled: true
url: jdbc:dm://localhost:5236/yourdb
username: yourusername
password: yourpassword
driverClassName: dm.jdbc.driver.DmDriver
# 初始连接数
initialSize: 5
# 最小连接池数量
minIdle: 10
# 最大连接池数量
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
3、配置多数据源信息
位置:在DruidConfig类中配置多数据源的信息
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties("spring.datasource.druid.master")
public DataSource masterDataSource(DruidProperties druidProperties) {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean
@ConfigurationProperties("spring.datasource.druid.slave")
@ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
public DataSource slaveDataSource(DruidProperties druidProperties) {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
}
在需要切换数据源的
service
层或单个方法上加上注解@DataSource(value =DataSourceType.SLAVE)
默认情况下使用主数据源
MASTER
@Service
@DataSource(value = DataSourceType.SLAVE)
@Transactional
public class TestServiceImpl extends implements ITestService
{
@Autowired
private TestMappertestMapper;
@Override
public User selectAll()
{
return testMapper.selectAll();
}
}
@Service
@Transactional
public class TestServiceImpl extends implements ITestService
{
@Autowired
private TestMappertestMapper;
@Override
@DataSource(value = DataSourceType.SLAVE)
public User selectAll()
{
return testMapper.selectAll();
}
}
powered by kaifamiao