栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot+apollo+mybatis动态切换数据库

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot+apollo+mybatis动态切换数据库

一、Apollo简介

这是一个可以动态获取配置并生效,不用重启服务的框架。
https://github.com/apolloconfig/apollo-build-scripts
搭建方式就不多说了,参考文档

我们准备好了一个Quick Start安装包,大家只需要下载到本地,就可以直接使用,免去了编译、打包过程。

安装包共50M,如果访问github网速不给力的话,可以从百度网盘下载。

从Github下载 checkout或下载apollo-build-scripts项目 从百度网盘下载 通过网盘链接下载,提取码: 9wwe
下载到本地后,在本地解压apollo-quick-start.zip 为啥安装包要58M这么大?
因为这是一个可以自启动的jar包,里面包含了所有依赖jar包以及一个内置的tomcat容器

二、搭建一个spring boot项目(略) 三、spring boot mybatis多数据源配置
@Configuration
//扫对应mapper interface 的包路径
@MapperScan(basePackages = "com.apollo.demo.mapper.read", sqlSessionTemplateRef  = "readSqlSessionTemplate")
public class ReadMysqlConfig {

    @Bean(name = "readDataSource")
    //配置文件中数据库配置
    @ConfigurationProperties(prefix = "spring.datasource.read")
    public DataSource tefpDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        //将beanName放进map放便动态更新数据库配置
        DataSourceConfig.dsreload.put("spring.datasource.read.url", "readDataSource");
        return dataSource;
    }

    @Bean(name = "readSqlSessionFactory")
    public SqlSessionFactory tefpSqlSessionFactory(@Qualifier("readDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //mapper.xml文件路径
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/read*.xml
                    **/*.properties
                
                true
            

DataSourceConfig中为什么要两次重启
DruidAbstractDataSource setUrl()方法只要初始化之后就不能修改了

public void setUrl(String jdbcUrl) {
        if (StringUtils.equals(this.jdbcUrl, jdbcUrl)) {
            return;
        }

        if (inited) {
            throw new UnsupportedOperationException();
        }

        if (jdbcUrl != null) {
            jdbcUrl = jdbcUrl.trim();
        }

        this.jdbcUrl = jdbcUrl;

        // if (jdbcUrl.startsWith(ConfigFilter.URL_PREFIX)) {
        // this.filters.add(new ConfigFilter());
        // }
    }

但是它的restart()方法会讲初始化状态恢复到false

public void restart() throws SQLException {
        lock.lock();
        try {
            if (activeCount > 0) {
                throw new SQLException("can not restart, activeCount not zero. " + activeCount);
            }
            if (LOG.isInfoEnabled()) {
                LOG.info("{dataSource-" + this.getID() + "} restart");
            }

            this.close();
            this.resetStat();
            this.inited = false;
            this.enable = true;
            this.closed = false;
        } finally {
            lock.unlock();
        }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/970844.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号