springboot中怎么配置多数据源-成都快上网建站

springboot中怎么配置多数据源

这篇文章给大家介绍springboot中怎么配置多数据源,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

我们拥有十年网页设计和网站建设经验,从网站策划到网站制作,我们的网页设计师为您提供的解决方案。为企业提供网站设计制作、网站设计、微信开发、成都微信小程序、手机网站开发、H5高端网站建设、等业务。无论您有什么样的网站设计或者设计方案要求,我们都将富于创造性的提供专业设计服务并满足您的需求。

配置文件数据源读取

通过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 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 getExtraDataSourc();
}

获取对应Service的所有实现类进行调用

    private List getExtraDataSource(){
        List dataSourceModelList = new ArrayList<>();
        Map 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 contextHolder = new ThreadLocal();// 调用此方法,切换数据源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

关于springboot中怎么配置多数据源就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


网页标题:springboot中怎么配置多数据源
标题URL:http://kswjz.com/article/iepcei.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流