目录
- 1. 方式一
- 2. 方式二(常用)
1. 方式一
采用jpa的依赖包:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
配置对应的数据源:application.properties
# 主数据源配置
spring.datasource.primary.url=jdbc:mysql://localhost:3306/primarydb
spring.datasource.primary.username=username
spring.datasource.primary.password=password
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver# 辅助数据源配置
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/secondarydb
spring.datasource.secondary.username=username
spring.datasource.secondary.password=password
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
创建数据源配置:
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {@Primary@Bean(name = "primaryDataSource")@ConfigurationProperties(prefix = "spring.datasource.primary")public DataSource primaryDataSource() {return DataSourceBuilder.create().build();}@Bean(name = "secondaryDataSource")@ConfigurationProperties(prefix = "spring.datasource.secondary")public DataSource secondaryDataSource() {return DataSourceBuilder.create().build();}@Primary@Bean(name = "entityManagerFactory")public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("primaryDataSource") DataSource dataSource) {return builder.dataSource(dataSource).packages("your.primary.entity.package").persistenceUnit("primary").build();}@Bean(name = "secondaryEntityManagerFactory")public LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("secondaryDataSource") DataSource dataSource) {return builder.dataSource(dataSource).packages("your.secondary.entity.package").persistenceUnit("secondary").build();}@Primary@Bean(name = "transactionManager")public PlatformTransactionManager transactionManager(@Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {return new JpaTransactionManager(entityManagerFactory);}@Bean(name = "secondaryTransactionManager")public PlatformTransactionManager secondaryTransactionManager(@Qualifier("secondaryEntityManagerFactory") EntityManagerFactory entityManagerFactory) {return new JpaTransactionManager(entityManagerFactory);}
}
切换数据源,此处使用@Qualifier
的注解
@Service
public class YourService {@Autowired@Qualifier("primaryDataSource")private DataSource primaryDataSource;@Autowired@Qualifier("secondaryDataSource")private DataSource secondaryDataSource;@Autowiredprivate YourRepository yourRepository;@Transactional(transactionManager = "transactionManager")public void methodUsingPrimaryDataSource() {// 在这里使用主数据源}@Transactional(transactionManager = "secondaryTransactionManager")public void methodUsingSecondaryDataSource() {// 在这里使用辅助数据源}
}
2. 方式二(常用)
配置依赖包:
<dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId>
</dependency>
先配置数据源:
spring:datasource:dynamic: # 多数据源配置druid: # Druid 【连接池】相关的全局配置initial-size: 1 # 初始连接数min-idle: 1 # 最小连接池数量max-active: 20 # 最大连接池数量max-wait: 600000 # 配置获取连接等待超时的时间,单位:毫秒time-between-eviction-runs-millis: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位:毫秒min-evictable-idle-time-millis: 300000 # 配置一个连接在池中最小生存的时间,单位:毫秒max-evictable-idle-time-millis: 900000 # 配置一个连接在池中最大生存的时间,单位:毫秒validation-query: SELECT 1 FROM DUAL # 配置检测连接是否有效test-while-idle: truetest-on-borrow: falsetest-on-return: falseprimary: masterdatasource:master:name: manongurl: jdbc:mysql://10.197.2.223:3306/${spring.datasource.dynamic.datasource.master.name}?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true # MySQL Connector/J 8.X 连接的示例username: rootpassword: rootslave:name: manonglazy: true # 开启懒加载,保证启动速度url: jdbc:mysql://10.197.2.223:3306/${spring.datasource.dynamic.datasource.slave.name}?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true # MySQL Connector/J 8.X 连接的示例username: rootpassword: rootss:name: sslazy: true # 开启懒加载,保证启动速度url: jdbc:oracle:thin:@//10.197.1.200:3333/ss # Oracle 连接的示例username: rootpassword: root
之后调用的时候采取@Master
或者@Slave
的形式,使用哪个注解就是使用哪个数据库
也可采用@DS的注解形式,对于多数据源来说
自定义注解如下:
import org.springframework.core.annotation.AliasFor;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Master {
}
import org.springframework.core.annotation.AliasFor;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Slave {
}
定义自定义事务注解 @DSTransactional
import org.springframework.transaction.annotation.Transactional;
import java.lang.annotation.*;@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional("dynamicTransactionManager")
public @interface DSTransactional {
}
Service层如下:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;@Service
public class YourService {private final JdbcTemplate masterJdbcTemplate;private final JdbcTemplate slaveJdbcTemplate;@Autowiredpublic YourService(@Qualifier("masterJdbcTemplate") JdbcTemplate masterJdbcTemplate,@Qualifier("slaveJdbcTemplate") JdbcTemplate slaveJdbcTemplate) {this.masterJdbcTemplate = masterJdbcTemplate;this.slaveJdbcTemplate = slaveJdbcTemplate;}@Masterpublic void doSomethingWithMaster() {// 使用主数据源进行操作}@Slavepublic void doSomethingWithSlave() {// 使用从数据源进行操作}@DSTransactionalpublic void doSomethingTransactional() {// 这个方法将使用默认数据源进行操作,因为 @Transactional 注解没有指定数据源}
}