SpringBoot中使用动态数据源可以实现分布式中的分库技术,比如查询用户 就在用户库中查询,查询订单 就在订单库中查询。

一、配置文件application.properties

# 默认数据源
spring.datasource.url=jdbc:mysql://localhost:3306/consult
spring.datasource.username=myConsult
spring.datasource.password=123456
spring.datasource.driver-class-name=org.gjt.mm.mysql.Driver
# 更多数据源
custom.datasource.names=ds1,ds2
custom.datasource.ds1.driver-class-name=com.mysql.jdbc.Driver
custom.datasource.ds1.url=jdbc:mysql://localhost:3306/test1
custom.datasource.ds1.username=root
custom.datasource.ds1.password=123456
custom.datasource.ds2.driver-class-name=com.mysql.jdbc.Driver
custom.datasource.ds2.url=jdbc:mysql://localhost:3306/test2
custom.datasource.ds2.username=root
custom.datasource.ds2.password=123456

二、pox.xml

 <!-- aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>

三、使用aop自定义注解,实现动态切换数据源

1.动态数据源注册器

 package com.xsjt.dynamicDataSource;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
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 org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
/**
* ClassName:DynamicDataSourceRegister
* Date: 2017年11月13日 下午7:40:42
* @author Joe
* @version
* @since JDK 1.8
*/
public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceRegister.class); private ConversionService conversionService = new DefaultConversionService();
private PropertyValues dataSourcePropertyValues; // 如配置文件中未指定数据源类型,使用该默认值
private static final Object DATASOURCE_TYPE_DEFAULT = "org.apache.tomcat.jdbc.pool.DataSource"; // private static final Object DATASOURCE_TYPE_DEFAULT = "com.zaxxer.hikari.HikariDataSource"; // 数据源
private DataSource defaultDataSource; private Map<String, DataSource> customDataSources = new HashMap<String, DataSource>(); 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 = beanDefinition.getPropertyValues();
mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
mpv.addPropertyValue("targetDataSources", targetDataSources);
registry.registerBeanDefinition("dataSource", beanDefinition); // 注册到Spring容器中 logger.info("Dynamic DataSource Registry");
} /**
* 创建DataSource
* @param type
* @param driverClassName
* @param url
* @param username
* @param password
* @return
*/
@SuppressWarnings("unchecked")
public DataSource buildDataSource(Map<String, Object> dsMap) {
try {
Object type = dsMap.get("type");
if (type == null)
type = DATASOURCE_TYPE_DEFAULT;// 默认DataSource Class<? extends DataSource> dataSourceType;
dataSourceType = (Class<? extends DataSource>)Class.forName((String)type); String driverClassName = dsMap.get("driver-class-name").toString();
String url = dsMap.get("url").toString();
String username = dsMap.get("username").toString();
String password = dsMap.get("password").toString(); DataSourceBuilder factory = DataSourceBuilder.create()
.driverClassName(driverClassName)
.url(url)
.username(username)
.password(password)
.type(dataSourceType);
return factory.build();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
} /**
* 加载多数据源配置
*/
public void setEnvironment(Environment env) {
initDefaultDataSource(env);
initCustomDataSources(env);
} /**
* 初始化主数据源
*/
private void initDefaultDataSource(Environment env) {
// 读取主数据源
RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
Map<String, Object> dsMap = new HashMap<String, Object>();
dsMap.put("type", propertyResolver.getProperty("type"));
dsMap.put("driver-class-name",propertyResolver.getProperty("driver-class-name"));
dsMap.put("url", propertyResolver.getProperty("url"));
dsMap.put("username", propertyResolver.getProperty("username"));
dsMap.put("password", propertyResolver.getProperty("password"));
defaultDataSource = buildDataSource(dsMap);
dataBinder(defaultDataSource, env);
} /**
* 为DataSource绑定更多数据
* @param dataSource
* @param env
*/
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, "spring.datasource").getSubProperties(".");
Map<String, Object> values = new HashMap<String, Object>(rpr);
// 排除已经设置的属性
values.remove("type");
values.remove("driver-class-name");
values.remove("url");
values.remove("username");
values.remove("password");
dataSourcePropertyValues = new MutablePropertyValues(values);
}
dataBinder.bind(dataSourcePropertyValues);
} /**
* 初始化更多数据源
*
*/
private void initCustomDataSources(Environment env) {
// 读取配置文件获取更多数据源,也可以通过defaultDataSource读取数据库获取更多数据源
RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver( env, "custom.datasource.");
String dsPrefixs = propertyResolver.getProperty("names");
for (String dsPrefix : dsPrefixs.split(",")) {// 多个数据源
Map<String, Object> dsMap = propertyResolver.getSubProperties(dsPrefix + ".");
DataSource ds = buildDataSource(dsMap);
customDataSources.put(dsPrefix, ds);
dataBinder(ds, env);
}
}
}

2.动态数据源适配器

package com.xsjt.dynamicDataSource;
import java.util.ArrayList;
import java.util.List;
/**
* ClassName:DynamicDataSourceContextHolder
* Date: 2017年11月13日 下午7:41:49
* @author Joe
* @version
* @since JDK 1.8
*/
public class DynamicDataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static List<String> dataSourceIds = new ArrayList<String>(); public static void setDataSourceType(String dataSourceType) {
contextHolder.set(dataSourceType);
} public static String getDataSourceType() {
return contextHolder.get();
} public static void clearDataSourceType() {
contextHolder.remove();
} /**
* 判断指定DataSrouce当前是否存在
*
* @param dataSourceId
* @return
*/
public static boolean containsDataSource(String dataSourceId){
return dataSourceIds.contains(dataSourceId);
}
}

3.自定义注解

/**
* ClassName:TargetDataSource
* Date: 2017年11月13日 下午7:42:15
* @author Joe
* @version
* @since JDK 1.8
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
String name();
}

4.动态数据源切面

package com.xsjt.dynamicDataSource;
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 org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* ClassName:DynamicDataSourceAspect
* Date: 2017年11月13日 下午7:44:09
* @author Joe
* @version
* @since JDK 1.8
*/
@Aspect
//保证该AOP在@Transactional之前执行
@Order(-1)
@Component
public class DynamicDataSourceAspect {
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class); /**
* @Description 在方法执行之前执行 @annotation(ds) 会拦截有ds这个注解的方法即有 TargetDataSource这个注解的
* @param @param point
* @param @param ds
* @param @throws Throwable 参数
* @return void 返回类型
* @throws
*/
@Before("@annotation(ds)")
public void changeDataSource(JoinPoint point, TargetDataSource ds)
throws Throwable {
String dsId = ds.name();
if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
logger.error("数据源[{}]不存在,使用默认数据源 > {}", ds.name(), point.getSignature());
}
else {
logger.debug("Use DataSource : {} > {}", ds.name(),point.getSignature());
DynamicDataSourceContextHolder.setDataSourceType(ds.name());
}
} /**
* @Description 在方法执行之后执行 @annotation(ds) 会拦截有ds这个注解的方法即有 TargetDataSource这个注解的
* @param @param point
* @param @param ds 参数
* @return void 返回类型
* @throws
*/
@After("@annotation(ds)")
public void restoreDataSource(JoinPoint point, TargetDataSource ds) {
logger.debug("Revert DataSource : {} > {}", ds.name(), point.getSignature());
DynamicDataSourceContextHolder.clearDataSourceType();
}
}

5.继承Spring AbstractRoutingDataSource实现路由切换

package com.xsjt.dynamicDataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* ClassName:DynamicDataSource
* 继承Spring AbstractRoutingDataSource实现路由切换
* Date: 2017年11月13日 下午7:49:49
* @author Joe
* @version
* @since JDK 1.8
*/
public class DynamicDataSource extends AbstractRoutingDataSource { @Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceType();
}
}

四、怎么使用自定义的注解动态的切换数据源

只需要在service实现类中 对需要切换数据源的方法上 加上 自定义的注解即可,如:@TargetDataSource(name = "ds2")

五、启动类上添加@Import注解

  //注册动态多数据源
  @Import({DynamicDataSourceRegister.class})

六.源码下载

  https://gitee.com/xbq168/spring-boot-learn

SpringBoot(十一)-- 动态数据源的更多相关文章

  1. Springboot+Druid 动态数据源配置监控

    一.引入maven依赖,使用 starter 与原生 druid 依赖配置有所不同 <dependency> <groupId>com.alibaba</groupId& ...

  2. SpringBoot和Mycat动态数据源项目整合

    SpringBoot项目整合动态数据源(读写分离) 1.配置多个数据源,根据业务需求访问不同的数据,指定对应的策略:增加,删除,修改操作访问对应数据,查询访问对应数据,不同数据库做好的数据一致性的处理 ...

  3. SpringBoot动态数据源

    1.原理图 2.创建枚举类 /** * 存数据源key值 */ public enum DataSourceKey { master,salve,migration } 3.创建自定义注解类 /** ...

  4. SpringBoot整合MyBatisPlus配置动态数据源

    目录 SpringBoot整合MyBatisPlus配置动态数据源 SpringBoot整合MyBatisPlus配置动态数据源 推文:2018开源中国最受欢迎的中国软件MyBatis-Plus My ...

  5. SpringBoot集成Mybatis配置动态数据源

    很多人在项目里边都会用到多个数据源,下面记录一次SpringBoot集成Mybatis配置多数据源的过程. pom.xml <?xml version="1.0" encod ...

  6. SpringBoot学习笔记:动态数据源切换

    SpringBoot学习笔记:动态数据源切换 数据源 Java的javax.sql.DataSource接口提供了一种处理数据库连接的标准方法.通常,DataSource使用URL和一些凭据来建立数据 ...

  7. SpringBoot之多数据源动态切换数据源

    原文:https://www.jianshu.com/p/cac4759b2684 实现 1.建库建表 首先,我们在本地新建三个数据库名分别为master,slave1,slave2,我们的目前就是写 ...

  8. springboot多数据源&动态数据源(主从)

    多数据源 使用Spring Boot时,默认情况下,配置DataSource非常容易.Spring Boot会自动为我们配置好一个DataSource. 如果在application.yml中指定了s ...

  9. 搞定SpringBoot多数据源(2):动态数据源

    目录 1. 引言 2. 动态数据源流程说明 3. 实现动态数据源 3.1 说明及数据源配置 3.1.1 包结构说明 3.1.2 数据库连接信息配置 3.1.3 数据源配置 3.2 动态数据源设置 3. ...

随机推荐

  1. e866. 确定可用外观

    UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels(); for (int i=0; i<info.len ...

  2. Php面向对象 – 类常量

    Php面向对象 – 类常量 类常量:类中,保存执行周期内,不变的数据. 定义: constkeyword const 常量名 = 常量值 样例: class Student { public  $st ...

  3. linux drwxr-xr-x 是什么意思

    linux drwxr-xr-x 第一位表示文件类型.d是目录文件,l是链接文件,-是普通文件,p是管道 第2-4位表示这个文件的属主拥有的权限,r是读,w是写,x是执行. 第5-7位表示和这个文件属 ...

  4. Jenkins+Github配置【转】

    一.GitHub上配置 前提:Jenkins能正常打开 将本地文件上传到GitHub上:进入终端 cd Documents cd project git clone https://github.co ...

  5. TensoFlow的tf.reshape()

    tf.reshape(tensor,shape,name=None) 函数的作用是将tensor变换为参数shape形式,其中的shape为一个列表形式,特殊的是列表可以实现逆序的遍历,即list(- ...

  6. Mac下终端使用密钥登录服务器

    可行方法: mac终端输入 ssh-keygen 因为mac系统是类unix系统,linux系统是unix系统演变来的,所以呢,相当于在一个linux系统登录另外一个linux系统, 基本命令还是一样 ...

  7. electron demo项目npm install安装失败解决办法

    electron官网提供的demo项目,在npm install 的时候总是报错显示安装失败, 解决办法:FQ即可成功安装.

  8. MongoDB之update

    Update操作只作用于集合中存在的文档.MongoDB提供了如下方法来更新集合中的文档: db.collection.update() db.collection.updateOne() New i ...

  9. Global.asax的Application_BeginRequest实现url重写无后缀的代码

    本文为大家详细介绍下利用Global.asax的Application_BeginRequest 实现url重写其无后缀,具体核心代码如下,有需求的朋友可以参考下,希望对大家有所帮助 利用Global ...

  10. Eclipse中项目全部报错----项目全部打红叉的解决办法

    今天遇到一个超级郁闷的事情,Eclipse新建的项目全部都打有红叉,我起初以为自 己可能是因为这两天一直在配置NDK开发环境方面的东西,是不是一不小心把那个地方给配置了,然后新建项目时项目都会出现红叉 ...