springboot进⾏动态数据源配置(基于注解⽅式)
⼀、应⽤场景
项⽬需要从⾃⼰的数据库上读取和管理数据外,还有⼀部分业务涉及到其他多个数据库。
为了能够灵活地指定具体的数据库,本⽂基于注解和AOP的⽅法实现多数据源⾃动切换。在使⽤过程中,只需要添加注解就可以使⽤,简单⽅便。
⼆、准备⼯作
2.1 创建数据表
USE test;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3DEFAULT CHARSET=utf8
USE test1;
CREATE TABLE `teacher` (
`tid` int(11) NOT NULL AUTO_INCREMENT,
`tname` varchar(255) NOT NULL,
`tage` int(11) NOT NULL,
PRIMARY KEY (`tid`)
) ENGINE=InnoDB AUTO_INCREMENT=3DEFAULT CHARSET=utf8
USE test2;
CREATE TABLE `student` (
`sid` int(11) NOT NULL AUTO_INCREMENT,
`sname` varchar(255) NOT NULL,
`sage` int(11) NOT NULL,
PRIMARY KEY (`sid`)
) ENGINE=InnoDB AUTO_INCREMENT=3DEFAULT CHARSET=utf8
2.2 添加依赖
spring boot:1.5.8.RELEASE
mysql:5.1.44
mybatis:1.3.2
druid:1.1.3
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId&le</groupId>
<artifactId>dynamic-data-source</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>dynamic-data-source</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/><!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
&porting.outputEncoding>UTF-8</porting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--mybatis-->
<dependency>
<groupId&batis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- mybatis generator ⾃动⽣成代码插件 -->
<plugin>
<groupId&ator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.3 ⽣成 bean、dao、mapper
使⽤MyBatis Generator⾃动⽣成,⽅法如下:
三、动态数据源
3.1 配置⽂件 application.properties custom.datasource.defaultname=default
custom.datasource.names=ds1,ds2
# 默认数据源
custom.datasource.sql.jdbc.Driver custom.datasource.url=jdbc:mysql://localhost:3306/test custom.datasource.username=root
custom.datasource.password=root
# 更多数据源
custom.datasource.ds1.sql.jdbc.Driver custom.datasource.ds1.url=jdbc:mysql://localhost:3306/test1 custom.datasource.ds1.username=root
custom.datasource.ds1.password=root
custom.datasource.ds2.sql.jdbc.Driver
custom.datasource.ds2.url=jdbc:mysql://localhost:3306/test2
custom.datasource.ds2.username=root
custom.datasource.ds2.password=root
custom.datasource.filters=stat
custom.datasource.maxActive=100
custom.datasource.initialSize=1
custom.datasource.minIdle=1
custom.datasource.timeBetweenEvictionRunsMillis=60000
custom.datasource.minEvictableIdleTimeMillis=300000
custom.datasource.validationQuery=select 'x'
stWhileIdle=true
stOnBorrow=false
stOnReturn=false
custom.datasource.poolPreparedStatements=true
custom.datasource.maxOpenPreparedStatements=100
mybatis.mapper-locations=classpath:mapper/**/*.xml
3.2 动态数据源核⼼代码
DynamicDataSource:动态数据源切换;
DynamicDataSourceAspect:利⽤AOP切⾯实现数据源的动态切换;DynamicDataSourceContextHolder:动态切换数据源;
DynamicDataSourceRegister:动态数据源注册;
TargetDataSource:在⽅法上使⽤,⽤于指定使⽤哪个数据源。
ample.demo.datasource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 动态数据源
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
DataSourceType();
}
}
ample.demo.datasource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import annotation.Order;
import org.springframework.stereotype.Component;
/**
* 切换数据源Advice
*/
@Aspect
@Order(-1)// 保证该AOP在@Transactional之前执⾏
@Component
public class DynamicDataSourceAspect {
springboot aopprivate static final Logger logger = Logger(DynamicDataSourceAspect.class); @Before("@annotation(ds)")
public void changeDataSource(JoinPoint point, TargetDataSource ds) throws Throwable {
String dsId = ds.name();
if (!ainsDataSource(dsId)) {
<("数据源[{}]不存在,使⽤默认数据源 > {}", ds.name(), Signature());
}else {
logger.debug("Use DataSource : {} > {}", dsId, Signature());
DynamicDataSourceContextHolder.setDataSourceType(dsId);
}
}
@After("@annotation(ds)")
public void restoreDataSource(JoinPoint point, TargetDataSource ds) {
logger.debug("Revert DataSource : {} > {}", ds.name(), Signature());
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
ample.demo.datasource;
import java.util.ArrayList;
import java.util.List;
public class DynamicDataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public static List<String> dataSourceIds = new ArrayList<>();
public static void setDataSourceType(String dataSourceType) {
contextHolder.set(dataSourceType);
}
public static String getDataSourceType() {
();
}
public static void clearDataSourceType() {
}
/**
* 判断指定DataSrouce当前是否存在
*/
public static boolean containsDataSource(String dataSourceId){
ains(dataSourceId);
}
}
ample.demo.datasource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.bind.RelaxedDataBinder;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import t.EnvironmentAware;
import t.annotation.ImportBeanDefinitionRegistrar;
import onvert.ConversionService;
import onvert.support.DefaultConversionService;
import nv.Environment;
import ype.AnnotationMetadata;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* 动态数据源注册
* 启动动态数据源请在启动类中添加 @Import(DynamicDataSourceRegister.class)
*/
public class DynamicDataSourceRegister
implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private static final Logger logger = Logger(DynamicDataSourceRegister.class); private ConversionService conversionService = new DefaultConversionService();
private PropertyValues dataSourcePropertyValues;
// 如配置⽂件中未指定数据源类型,使⽤该默认值
private static final Object DATASOURCE_TYPE_DEFAULT = "com.alibaba.druid.pool.DruidDataSource"; // 数据源
private DataSource defaultDataSource;
private Map<String, DataSource> customDataSources = new HashMap<>();
private static String DB_NAME = "names";
private static String DB_DEFAULT_VALUE = "custom.datasource"; //配置⽂件中前缀
@Value("${bi.datasource.defaultname}")
private String defaultDbname;
//加载多数据源配置
@Override
public void setEnvironment(Environment env) {
initDefaultDataSource(env);
initCustomDataSources(env);
}
//初始化主数据源
private void initDefaultDataSource(Environment env) {
// 读取主数据源
RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, DB_DEFAULT_VALUE+"."); Map<String, Object> dsMap = new HashMap<>();
dsMap.put("type", Property("type"));
dsMap.put("driver-class-name", Property("driver-class-name"));
dsMap.put("url", Property("url"));
dsMap.put("username", Property("username"));
dsMap.put("password", Property("password"));
defaultDataSource = buildDataSource(dsMap);
customDataSources.put(defaultDbname,defaultDataSource);//默认数据源放到动态数据源⾥
dataBinder(defaultDataSource, env);
}
//为DataSource绑定更多数据
private void dataBinder(DataSource dataSource, Environment env) {
RelaxedDataBinder dataBinder = new RelaxedDataBinder(dataSource);
//dataBinder.setValidator(new LocalValidatorFactory().run(this.applicationContext));
dataBinder.setConversionService(conversionService);
dataBinder.setIgnoreNestedProperties(false);//false
dataBinder.setIgnoreInvalidFields(false);//false
dataBinder.setIgnoreUnknownFields(true);//true
if (dataSourcePropertyValues == null) {
Map<String, Object> rpr = new RelaxedPropertyResolver(env, DB_DEFAULT_VALUE).getSubProperties("."); Map<String, Object> values = new HashMap<String, Object>(rpr);
// 排除已经设置的属性
dataSourcePropertyValues = new MutablePropertyValues(values);
}
dataBinder.bind(dataSourcePropertyValues);
}
//初始化更多数据源
private void initCustomDataSources(Environment env) {
/
/ 读取配置⽂件获取更多数据源,也可以通过defaultDataSource读取数据库获取更多数据源
RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env,DB_DEFAULT_VALUE+"."); String dsPrefixs = Property(DB_NAME);
for (String dsPrefix : dsPrefixs.split(",")) {// 多个数据源
Map<String, Object> dsMap = SubProperties(dsPrefix + ".");
DataSource ds = buildDataSource(dsMap);
customDataSources.put(dsPrefix, ds);
dataBinder(ds, env);
}
}
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
// 将主数据源添加到更多数据源中
targetDataSources.put("dataSource", defaultDataSource);
DynamicDataSourceContextHolder.dataSourceIds.add("dataSource");
// 添加更多数据源
targetDataSources.putAll(customDataSources);
for (String key : customDataSources.keySet()) {
DynamicDataSourceContextHolder.dataSourceIds.add(key);
}
// 创建DynamicDataSource
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(DynamicDataSource.class);
beanDefinition.setSynthetic(true);
MutablePropertyValues mpv = PropertyValues();
mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
mpv.addPropertyValue("targetDataSources", targetDataSources);
logger.info("Dynamic DataSource Registry");
}
//创建DataSource
@SuppressWarnings("unchecked")
public DataSource buildDataSource(Map<String, Object> dsMap) {
try {
Object type = ("type");
if (type == null)
type = DATASOURCE_TYPE_DEFAULT;// 默认DataSource
Class<? extends DataSource> dataSourceType;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论