springboot多数据源配置及切换的示例代码详解
注:本文的多数据源配置及切换的实现方法是,在框架中封装,具体项目中配置及使用,也适用于多模块项目
配置文件数据源读取
通过springboot的Envioment和Binder对象进行读取,无需手动声明DataSource的Bean
yml数据源配置格式如下:
spring: datasource: master: type: com.alibaba.druid.pool.DruidDataSource driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/main? useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai username: root password: 11111 cluster: - key: db1 type: com.alibaba.druid.pool.DruidDataSource driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/haopanframetest_db1? useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai username: root password: 11111 - key: db2 type: com.alibaba.druid.pool.DruidDataSource driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/haopanframetest_db2? useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai username: root password: 11111
master为主数据库必须配置,cluster下的为从库,选择性配置
获取配置文件信息代码如下
@Autowired private Environment env; @Autowired private ApplicationContext applicationContext; private Binder binder; binder = Binder.get(env); List<Map> configs = binder.bind("spring.datasource.cluster", Bindable.listOf(Map.class)).get(); for (int i = 0; i < configs.size(); i++) { config = configs.get(i); String key = ConvertOp.convert2String(config.get("key")); String type = ConvertOp.convert2String(config.get("type")); String driverClassName = ConvertOp.convert2String(config.get("driverClassName")); String url = ConvertOp.convert2String(config.get("url")); String username = ConvertOp.convert2String(config.get("username")); String password = ConvertOp.convert2String(config.get("password")); }
动态加入数据源
定义获取数据源的Service,具体项目中进行实现
public interface ExtraDataSourceService { List<DataSourceModel> getExtraDataSourc(); }
获取对应Service的所有实现类进行调用
private List<DataSourceModel> getExtraDataSource(){ List<DataSourceModel> dataSourceModelList = new ArrayList<>(); Map<String, ExtraDataSourceService> res = applicationContext.getBeansOfType(ExtraDataSourceService.class); for (Map.Entry en :res.entrySet()) { ExtraDataSourceService service = (ExtraDataSourceService)en.getValue(); dataSourceModelList.addAll(service.getExtraDataSourc()); } return dataSourceModelList; }
通过代码进行数据源注册
主要是用过继承类AbstractRoutingDataSource,重写setTargetDataSources/setDefaultTargetDataSource方法
// 创建数据源 public boolean createDataSource(String key, String driveClass, String url, String username, String password, String databasetype) { try { try { // 排除连接不上的错误 Class.forName(driveClass); DriverManager.getConnection(url, username, password);// 相当于连接数据库 } catch (Exception e) { return false; } @SuppressWarnings("resource") DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setName(key); druidDataSource.setDriverClassName(driveClass); druidDataSource.setUrl(url); druidDataSource.setUsername(username); druidDataSource.setPassword(password); druidDataSource.setInitialSize(1); //初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 druidDataSource.setMaxActive(20); //最大连接池数量 druidDataSource.setMaxWait(60000); //获取连接时最大等待时间,单位毫秒。当链接数已经达到了最大链接数的时候,应用如果还要获取链接就会出现等待的现象,等待链接释放并回到链接池,如果等待的时间过长就应该踢掉这个等待,不然应用很可能出现雪崩现象 druidDataSource.setMinIdle(5); //最小连接池数量 String validationQuery = "select 1 from dual"; druidDataSource.setTestOnBorrow(true); //申请连接时执行validationQuery检测连接是否有效,这里建议配置为TRUE,防止取到的连接不可用 druidDataSource.setTestWhileIdle(true);//建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 druidDataSource.setValidationQuery(validationQuery); //用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。 druidDataSource.setFilters("stat");//属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:监控统计用的filter:stat日志用的filter:log4j防御sql注入的filter:wall druidDataSource.setTimeBetweenEvictionRunsMillis(60000); //配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 druidDataSource.setMinEvictableIdleTimeMillis(180000); //配置一个连接在池中最小生存的时间,单位是毫秒,这里配置为3分钟180000 druidDataSource.setKeepAlive(true); //打开druid.keepAlive之后,当连接池空闲时,池中的minIdle数量以内的连接,空闲时间超过minEvictableIdleTimeMillis,则会执行keepAlive操作,即执行druid.validationQuery指定的查询SQL,一般为select * from dual,只要minEvictableIdleTimeMillis设置的小于防火墙切断连接时间,就可以保证当连接空闲时自动做保活检测,不会被防火墙切断 druidDataSource.setRemoveAbandoned(true); //是否移除泄露的连接/超过时间限制是否回收。 druidDataSource.setRemoveAbandonedTimeout(3600); //泄露连接的定义时间(要超过最大事务的处理时间);单位为秒。这里配置为1小时 druidDataSource.setLogAbandoned(true); //移除泄露连接发生是是否记录日志 druidDataSource.init(); this.dynamicTargetDataSources.put(key, druidDataSource); setTargetDataSources(this.dynamicTargetDataSources);// 将map赋值给父类的TargetDataSources super.afterPropertiesSet();// 将TargetDataSources中的连接信息放入resolvedDataSources管理 log.info(key+"数据源初始化成功"); //log.info(key+"数据源的概况:"+druidDataSource.dump()); return true; } catch (Exception e) { log.error(e + ""); return false; } }
通过切面注解统一切换
定义注解
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) @Documented public @interface TargetDataSource { String value() default "master"; //该值即key值 }
定义基于线程的切换类
public class DBContextHolder { private static Logger log = LoggerFactory.getLogger(DBContextHolder.class); // 对当前线程的操作-线程安全的 private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); // 调用此方法,切换数据源 public static void setDataSource(String dataSource) { contextHolder.set(dataSource); log.info("已切换到数据源:{}",dataSource); } // 获取数据源 public static String getDataSource() { return contextHolder.get(); } // 删除数据源 public static void clearDataSource() { contextHolder.remove(); log.info("已切换到主数据源"); } }
定义切面
方法的注解优先级高于类注解,一般用于Service的实现类
@Aspect @Component @Order(Ordered.HIGHEST_PRECEDENCE) public class DruidDBAspect { private static Logger logger = LoggerFactory.getLogger(DruidDBAspect.class); @Autowired private DynamicDataSource dynamicDataSource; /** * 切面点 指定注解 * */ @Pointcut("@annotation(com.haopan.frame.common.annotation.TargetDataSource) " + "|| @within(com.haopan.frame.common.annotation.TargetDataSource)") public void dataSourcePointCut() { } /** * 拦截方法指定为 dataSourcePointCut * */ @Around("dataSourcePointCut()") public Object around(ProceedingJoinPoint point) throws Throwable { MethodSignature signature = (MethodSignature) point.getSignature(); Class targetClass = point.getTarget().getClass(); Method method = signature.getMethod(); TargetDataSource targetDataSource = (TargetDataSource)targetClass.getAnnotation(TargetDataSource.class); TargetDataSource methodDataSource = method.getAnnotation(TargetDataSource.class); if(targetDataSource != null || methodDataSource != null){ String value; if(methodDataSource != null){ value = methodDataSource.value(); }else { value = targetDataSource.value(); } DBContextHolder.setDataSource(value); logger.info("DB切换成功,切换至{}",value); } try { return point.proceed(); } finally { logger.info("清除DB切换"); DBContextHolder.clearDataSource(); } } }
分库切换
开发过程中某个库的某个表做了拆分操作,相同的某一次数据库操作可能对应到不同的库,需要对方法级别进行精确拦截,可以定义一个业务层面的切面,规定每个方法必须第一个参数为dbName,根据具体业务找到对应的库传参
@Around("dataSourcePointCut()") public Object around(ProceedingJoinPoint point) throws Throwable { MethodSignature signature = (MethodSignature) point.getSignature(); Class targetClass = point.getTarget().getClass(); Method method = signature.getMethod(); ProjectDataSource targetDataSource = (ProjectDataSource)targetClass.getAnnotation(ProjectDataSource.class); ProjectDataSource methodDataSource = method.getAnnotation(ProjectDataSource.class); String value = ""; if(targetDataSource != null || methodDataSource != null){ //获取方法定义参数 DefaultParameterNameDiscoverer discover = new DefaultParameterNameDiscoverer(); String[] parameterNames = discover.getParameterNames(method); //获取传入目标方法的参数 Object[] args = point.getArgs(); for (int i=0;i<parameterNames.length;i++){ String pName = parameterNames[i]; if(pName.toLowerCase().equals("dbname")){ value = ConvertOp.convert2String(args[i]); } } if(!StringUtil.isEmpty(value)){ DBContextHolder.setDataSource(value); logger.info("DB切换成功,切换至{}",value); } } try { return point.proceed(); } finally { if(!StringUtil.isEmpty(value)){ logger.info("清除DB切换"); DBContextHolder.clearDataSource(); } } }
相关代码
到此这篇关于springboot多数据源配置及切换的示例代码详解的文章就介绍到这了,更多相关springboot多数据源配置 内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!
相关文章
IntelliJ IDEA2021.1 配置大全(超详细教程)
这篇文章主要介绍了IntelliJ IDEA2021.1 配置大全(超详细教程),需要的朋友可以参考下...2021-04-18- VPN可以虚拟出一个专用网络,让远处的计算机和你相当于处在同一个局域网中,而中间的数据也可以实现加密传输,用处很大,特别是在一些大公司,分公司处在不同的区域。...2016-01-27
- 这篇文章主要介绍了Tomcat配置及如何在Eclipse中启动,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-02-04
- 如果我们需要安培Laravel4的话最php最低要求要在php5.3.7版本并且我们需要把mcrypt与openss这两个扩展开启才可以,具体步骤我们参考下文。 前面我们介绍我了 com...2016-11-25
解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题
这篇文章主要介绍了解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-04-28- 下面小编就为大家带来一篇利用JS实现点击按钮后图片自动切换的简单方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-10-25
- 这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
详解Maven profile配置管理及激活profile的几种方式
这篇文章主要介绍了详解Maven profile配置管理及激活profile的几种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-26- 这篇文章主要介绍了详解springBoot启动时找不到或无法加载主类解决办法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-16
- 这篇文章主要介绍了SpringBoot集成Redis实现消息队列的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-10
- vue项目中有一些方法需要在多个页面调用,但为了避免在每个页面都import进来,可以把方法加到原型上去,这样在每个组件中都能使用了,下面这篇文章主要给大家介绍了关于配置vue全局方法的两种方式,需要的朋友可以参考下...2021-09-13
- 这篇文章主要介绍了js组件SlotMachine实现图片切换效果制作抽奖系统的相关资料,需要的朋友可以参考下...2016-04-19
- 这篇文章主要介绍了IDEA如何添加配置文件到classpath中,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-09-19
- 通常php.ini的位置在:复制代码 代码如下:/etc目录下或/usr/local/lib目录下。如果你还是找不到php.ini或者找到了php.ini修改后不生效(其实是没找对),请使用如下办法:1.新建php文件,写入如下代码复制代码 代码如下:<?phpe...2014-05-31
- 以下就是部署PHP时的4个配置修改说明,大家一个一个进行学习研究。1、short_open_tag 是什么呢? 决定是否允许使用代码开始标志的缩写形式(<? ?> )。如果要和 XML 结合使用PHP,可以禁用此选项以便于嵌入使用<?x...2015-10-21
- 这篇文章主要介绍了解决Springboot get请求是参数过长的情况,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-17
- 这篇文章主要介绍了Springboot+TCP监听服务器搭建过程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-10-28
华为畅享20Pro配置怎么样?华为畅享20Pro参数配置分析
华为畅享20Pro配置怎么样?对于即将上市的华为畅享20 Pro手机,很多的网友们也是相当关注的,大家都想要知道这款华为畅享20 Pro手机的配置到底怎么样,赶紧看看吧...2020-06-29Spring Boot项目@RestController使用重定向redirect方式
这篇文章主要介绍了Spring Boot项目@RestController使用重定向redirect方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-02- 这篇文章主要介绍了springBoot 项目排除数据库启动方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-10