springboot中怎么配置多数据源

发布时间:2021-07-13 11:25:56 作者:Leah
来源:亿速云 阅读:174

这篇文章给大家介绍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下的为从库,选择性配置

获取配置文件信息代码如下

    @Autowiredprivate Environment env;@Autowiredprivate 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:walldruidDataSource.setTimeBetweenEvictionRunsMillis(60000); //配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒druidDataSource.setMinEvictableIdleTimeMillis(180000); //配置一个连接在池中最小生存的时间,单位是毫秒,这里配置为3分钟180000druidDataSource.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赋值给父类的TargetDataSourcessuper.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})@Documentedpublic @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);@Autowiredprivate 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中怎么配置多数据源就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. springboot 基于mybatis如何实现配置多数据源
  2. SpringBoot如何配置MongoDB多数据源

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring boot

上一篇:android中手机方向传感器的缺点是什么

下一篇:selenium+python截图不成功怎么办

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》