前言:本方案来自若依框架,跟着学习搭建并测试。完美实现了多数据源的动态切换。
首先在SpringBoot项目的pom.xml中,引入相关jar
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.2.2
mysql
mysql-connector-java
runtime
com.alibaba
druid-spring-boot-starter
1.2.11
org.springframework.boot
spring-boot-starter-aop
org.projectlombok
lombok
1.18.4
org.springframework.boot
spring-boot-starter-test
test
yml配置mybatis扫描包路径以及数据源参数如下
#MyBatis
mybatis:
type-aliases-package: com.example.dbtest.mapper
mapper-locations: classpath:mapper/*.xml
#Spring
spring:
datasource:
druid:
master:
url: jdbc:mysql://xxxxxx:3306/xxxx?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true
username: root
password: woshidashuaiB
slave:
enabled: true
url: jdbc:mysql://xxxxxxxx:3306/xxx?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true
username: root
password: woshidashuaiB
min-idle: 10
initial-size: 5
max-active: 20
max-wait: 60000
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: true
test-on-borrow: false
test-on-return: false
web-stat-filter:
enabled: true
stat-view-servlet:
enabled: true
allow:
url-pattern: /druid/*
login-username: admin
login-password: woshidashuaiB
filter:
stat:
enabled: true
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
wall:
config:
multi-statement-allow: true
db-type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
server:
port: 8080
自定义数据源切换的注解
package com.example.dbtest.config;
import java.lang.annotation.*;
/**
* 数据源切换自定义注解
* @Author dashuaiB
* @Date 2022/7/4 17:45
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DataSource {
public DataSourceType value() default DataSourceType.MASTER;
}
数据源类型枚举类
package com.example.dbtest.config;
/**
* @Author dashuaiB
* @Date 2022/7/4 17:44
*/
public enum DataSourceType {
/**
* 主库
*/
MASTER,
/**
* 从库
*/
SLAVE
}
配置切面拦截
package com.example.dbtest.config;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* @Author dashuaiB
* @Date 2022/7/4 17:44
*/
@Aspect
@Order(1) // 优先级
@Component
public class DataSourceAspect {
/**
* 通过自定义注解@DataSource定义切点
*/
@Pointcut("@annotation(com.example.dbtest.config.DataSource)"
+ "|| @within(com.example.dbtest.config.DataSource)")
public void dsPointCut() {
}
/**
* 切点环绕
* @param point
* @return
* @throws Throwable
*/
@Around("dsPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
DataSource dataSource = getDataSource(point);
if (dataSource!=null) {
DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
}
try {
return point.proceed();
} finally {
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
/**
* 获取需要切换的数据源
*/
public DataSource getDataSource(ProceedingJoinPoint point) {
MethodSignature signature = (MethodSignature) point.getSignature();
Class extends Object> targetClass = point.getTarget().getClass();
DataSource targetDataSource = targetClass.getAnnotation(DataSource.class);
if (targetDataSource!=null) {
return targetDataSource;
} else {
Method method = signature.getMethod();
DataSource dataSource = method.getAnnotation(DataSource.class);
return dataSource;
}
}
}
数据源配置元数据
package com.example.dbtest.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* @Author dashuaiB
* @Date 2022/7/4 17:39
*/
@Configuration
public class DruidProperties {
@Value("${spring.datasource.druid.initial-size: 6}")
private int initialSize;
@Value("${spring.datasource.druid.min-idle}")
private int minIdle;
@Value("${spring.datasource.druid.max-active}")
private int maxActive;
@Value("${spring.datasource.druid.max-wait}")
private int maxWait;
@Value("${spring.datasource.druid.time-between-eviction-runs-millis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.druid.min-evictable-idle-time-millis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.druid.max-evictable-idle-time-millis}")
private int maxEvictableIdleTimeMillis;
@Value("${spring.datasource.druid.validation-query}")
private String validationQuery;
@Value("${spring.datasource.druid.test-while-idle}")
private boolean testWhileIdle;
@Value("${spring.datasource.druid.test-on-borrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.druid.test-on-return}")
private boolean testOnReturn;
public DruidDataSource dataSource(DruidDataSource datasource) {
/** 配置初始化大小、最小、最大 */
datasource.setInitialSize(initialSize);
datasource.setMaxActive(maxActive);
datasource.setMinIdle(minIdle);
/** 配置获取连接等待超时的时间 */
datasource.setMaxWait(maxWait);
/** 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 */
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
/** 配置一个连接在池中最小、最大生存的时间,单位是毫秒 */
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis);
/**
* 用来检测连接是否有效的sql,要求是一个查询语句,常用select
* 'x'。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。
*/
datasource.setValidationQuery(validationQuery);
/**
* 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
*/
datasource.setTestWhileIdle(testWhileIdle);
/** 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */
datasource.setTestOnBorrow(testOnBorrow);
/** 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */
datasource.setTestOnReturn(testOnReturn);
return datasource;
}
}
数据源配置
package com.example.dbtest.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.servlet.*;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @Author dashuaiB
* @Date 2022/7/4 17:42
*/
@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);
}
@Bean(name = "dynamicDataSource")
@Primary
public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource) {
Map
动态数据源切换上下文
package com.example.dbtest.config;
import lombok.extern.slf4j.Slf4j;
/**
* @Author dashuaiB
* @Date 2022/7/4 17:37
*/
@Slf4j
public class DynamicDataSourceContextHolder {
private static final ThreadLocal CONTEXT_HOLDER = new ThreadLocal<>();
public static void setDataSourceType(String dataSourceType) {
log.info("切换到{}数据库",dataSourceType);
CONTEXT_HOLDER.set(dataSourceType);
}
public static String getDataSourceType() {
return CONTEXT_HOLDER.get();
}
public static void clearDataSourceType() {
CONTEXT_HOLDER.remove();
}
}
动态数据源处理
package com.example.dbtest.config;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.Map;
/**
* @Author dashuaiB
* @Date 2022/7/4 17:38
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceType();
}
public DynamicDataSource(DataSource defaultTargetDataSource, Map
至此,所有工作已完成,完整项目结构如下:
两个库分别插入不同数据(左从右主)
编写mapper
@Repository
public interface TestMapper {
List getList();
List getList2();
}
编写service
@Service
//不指定数据源则默认访问主库
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Override
public List getList() {
return testMapper.getList();
}
@Override
//配置访问从库
@DataSource(DataSourceType.SLAVE)
public List getList2() {
return testMapper.getList2();
}
}
编写controller
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private TestService testService;
@GetMapping("/get")
public List getList(){
return testService.getList();
}
@GetMapping("/get2")
public List getList2(){
return testService.getList2();
}
}
启动应用
@SpringBootApplication
@MapperScan(basePackages = "com.example.dbtest.mapper")
public class DbtestApplication {
public static void main(String[] args) {
SpringApplication.run(DbtestApplication.class, args);
}
}
对主库的访问如下:
日志:
对从库的访问如下:
日志: