广告
返回顶部
首页 > 资讯 > 后端开发 > Python >MyBatis使用Zookeeper保存数据库的配置可动态刷新的实现代码
  • 754
分享到

MyBatis使用Zookeeper保存数据库的配置可动态刷新的实现代码

2024-04-02 19:04:59 754人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

核心关键点: 封装一个DataSource, 重写 getConnection 就可以实现 我们一步一步来看. 环境: spring cloud + mybatis MyBatis常

核心关键点: 封装一个DataSource, 重写 getConnection 就可以实现

我们一步一步来看.

环境: spring cloud + mybatis

MyBatis常规方式下配置数据源: 使用spring的Configuration


package com.cnscud.cavedemo.fundmain.config;


import com.cnscud.xpower.dbn.SimpleDBNDataSourceFactory;
import org.apache.ibatis.session.sqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatfORMTransactionManager;

import javax.sql.DataSource;


@Configuration
@MapperScan(basePackages = {"com.cnscud.cavedemo.fundmain.dao"},
        sqlSessionFactoryRef = "sqlSessionFactoryMainDataSource")
public class MainDataSourceConfig {



    //常规配置: 使用application.yml里面的配置.
    @Primary
    @Bean(name = "mainDataSource")
    @ConfigurationProperties("spring.datasource.main")
    public DataSource mainDataSource() throws Exception {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "sqlSessionFactoryMainDataSource")
    public SqlSessionFactory sqlSessionFactoryMainDataSource(@Qualifier("mainDataSource") DataSource mainDataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        //configuration.setMapUnderscoreToCamelCase(true);
        //factoryBean.setConfiguration(configuration);
        factoryBean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml"));

        // 使用mainDataSource数据源, 连接mainDataSource库
        factoryBean.setDataSource(mainDataSource);

        //下边两句仅仅用于*.xml文件,如果整个持久层操作不需要使用到xml文件的话(只用注解就可以搞定),则不加
        //指定entity和mapper xml的路径
        //factoryBean.setTypeAliasesPackage("com.cnscud.cavedemo.fundmain.model");
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/cnscud/cavedemo/fundmain/mapper
public class DynamicByZooKeeperDataSourceWrapper implements DataSource {

    protected SimpleDBNConnectionPool simpleDBNConnectionPool;
    protected String bizName;

    public DynamicByZookeeperDataSourceWrapper(SimpleDBNConnectionPool simpleDBNConnectionPool, String bizName) {
        this.simpleDBNConnectionPool = simpleDBNConnectionPool;
        this.bizName = bizName;
    }

    protected DataSource pickDataSource() throws SQLException{
        return simpleDBNConnectionPool.getDataSource(bizName);
    }

    @Override
    public Connection getConnection() throws SQLException {
        return pickDataSource().getConnection();
    }

    @Override
    public Connection getConnection(String username, String passWord) throws SQLException {
        return pickDataSource().getConnection(username, password);
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return pickDataSource().unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return pickDataSource().isWrapperFor(iface);
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return pickDataSource().getLogWriter();
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        pickDataSource().setLogWriter(out);
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        pickDataSource().setLoginTimeout(seconds);
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return pickDataSource().getLoginTimeout();
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new SQLFeatureNotSupportedException();
    }
}

SimpleDBNConnectionPool

支持多个数据源的暂存池, 可以根据name获取不同的数据库DataSource实例:

这个类负责创建DataSource, 保存在Map里. 并且能监听Zookeeper的变化, 一旦侦听到变化, 就close现有的DataSource.


package com.cnscud.xpower.dbn;

import com.GitHub.zkclient.IZkDataListener;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import static java.lang.String.format;


public class SimpleDBNConnectionPool {

    final Logger logger = LoggerFactory.getLogger(getClass());


    private Map<String, DataSource> instances = new ConcurrentHashMap<>();
    private final Set<String> watcherSchema = new HashSet<String>();


    public DataSource getInstance(String bizName) {
        try {
            return findDbInstance(bizName);
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Connection getConnection(String bizName) throws SQLException {
        DataSource ds = getDataSource(bizName);
        return ds.getConnection();
    }

    public DataSource getDataSource(String bizName) throws SQLException {
        return findDbInstance(bizName);
    }


    protected void destroyInstance(final String bizName) {
        synchronized (instances) {
            DataSource oldInstanceIf = instances.remove(bizName);
            logger.warn(format("destoryInstance %s and %s", bizName, oldInstanceIf != null ? "close datasource" : "do nothing"));
            if (oldInstanceIf != null) {
                closeDataSource(oldInstanceIf);
            }
        }
    }

    protected void closeDataSource(DataSource ds) {
        if (ds instanceof HikariDataSource) {
            try {
                ((HikariDataSource) ds).close();
            }
            catch (Exception e) {
                logger.error("Close datasource failed. ", e);
            }
        }
    }


    private DataSource createInstance(Map<String, String> dbcfg) {
        return new SimpleDataSourceBuilder().buildDataSource(dbcfg);
    }


    private DataSource findDbInstance(final String bizName) throws SQLException {
        DataSource ins = instances.get(bizName);
        if (ins != null) {
            return ins;
        }
        synchronized (instances) {// 同步操作
            ins = instances.get(bizName);
            if (ins != null) {
                return ins;
            }
            boolean success = false;
            try {
                Map<String, String> dbcfg = SchemenodeHelper.getInstance(bizName);
                if (dbcfg == null) {
                    throw new SQLException("No such datasouce: " + bizName);
                }
                ins = createInstance(dbcfg);
                //log.warn("ins put "+ins);
                instances.put(bizName, ins);


                if (watcherSchema.add(bizName)) {
                    SchemeNodeHelper.watchInstance(bizName, new IZkDataListener() {

                        public void handleDataDeleted(String dataPath) throws Exception {
                            logger.warn(dataPath + " was deleted, so destroy the bizName " + bizName);
                            destroyInstance(bizName);
                        }

                        public void handleDataChange(String dataPath, byte[] data) throws Exception {
                            logger.warn(dataPath + " was changed, so destroy the bizName " + bizName);
                            destroyInstance(bizName);
                        }
                    });
                }
                success = true;
            }
            catch (SQLException e) {
                throw e;
            }
            catch (Throwable t) {
                throw new SQLException("cannot build datasource for bizName: " + bizName, t);
            }
            finally {
                if (!success) {
                    instances.remove(bizName);
                }
            }
        }
        return ins;
    }

}

真正创建DataSource的代码:


package com.cnscud.xpower.dbn;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.lang.StringUtils;

import java.util.Map;


public class SimpleDataSourceBuilder {


    public HikariDataSource buildDataSource(Map<String, String> args) {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(getUrl(args));
        config.setUsername(args.get("username"));
        config.setPassword(args.get("password"));
        config.setDriverClassName(getDriverClassName(args));

        String maximumPoolSizeKey = "maximum-pool-size";
        int maximumPoolSize = 30;
        if(StringUtils.isNotEmpty(args.get(maximumPoolSizeKey))){
            maximumPoolSize = Integer.parseInt(args.get(maximumPoolSizeKey));
        }

        config.aDDDataSourceProperty("cachePrepStmts", "true"); //是否自定义配置,为true时下面两个参数才生效
        config.addDataSourceProperty("prepStmtCacheSize", maximumPoolSize); //连接池大小默认25,官方推荐250-500
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); //单条语句最大长度默认256,官方推荐2048
        config.addDataSourceProperty("useServerPrepStmts", "true"); //新版本Mysql支持服务器端准备,开启能够得到显著性能提升
        config.addDataSourceProperty("useLocalSessionState", "true");
        config.addDataSourceProperty("useLocalTransactionState", "true");
        config.addDataSourceProperty("rewriteBatchedStatements", "true");
        config.addDataSourceProperty("cacheResultSetMetadata", "true");
        config.addDataSourceProperty("cacheServerConfiguration", "true");
        config.addDataSourceProperty("elideSetAutoCommits", "true");
        config.addDataSourceProperty("maintainTimeStats", "false");

        config.setMaximumPoolSize(maximumPoolSize); //
        config.setMinimumIdle(10);//最小闲置连接数,默认为0
        config.setMaxLifetime(600000);//最大生存时间
        config.setConnectionTimeout(30000);//超时时间30秒
        config.setIdleTimeout(60000);

        config.setConnectionTestQuery("select 1");

        return new HikariDataSource(config);
    }

    private String getDriverClassName(Map<String, String> args) {
        return args.get("driver-class-name");
    }

    private String getUrl(Map<String, String> args) {
        return args.get("jdbc-url") == null ? args.get("url"): args.get("jdbc-url");
    }
}

为了方便读取Zookeeper节点, 还有个SchemeNodeHelper:

支持两种配置文件的方式 JSON或者Properties格式:


package com.cnscud.xpower.dbn;

import com.cnscud.xpower.confiGCenter.ConfigCenter;
import com.cnscud.xpower.utils.jsons;
import com.github.zkclient.IZkDataListener;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;


public class SchemeNodeHelper {

    static final Logger logger = LoggerFactory.getLogger(SchemeNodeHelper.class);

    //支持两种格式: json, properties
    public static Map<String, String> getInstance(final String instanceName) throws Exception {
        String data = ConfigCenter.getInstance().getDataAsString("/xpower/dbn/" + instanceName);
        if(StringUtils.isEmpty(data)){
            return null;
        }

        data = data.trim();
        if (data.startsWith("{")) {
            //as json
            Map<String, String> swap = Jsons.fromJson(data, Map.class);
            Map<String, String> result = new HashMap<>();

            if (swap != null) {
                for (String name : swap.keySet()) {
                    result.put(name.toLowerCase(), swap.get(name));
                }
            }

            return result;
        }
        else {
            //as properties
            Properties props = new Properties();
            try {
                props.load(new StringReader(data));
            }
            catch (IOException e) {
                logger.error("loading global config failed", e);
            }

            Map<String, String> result = new HashMap<>();

            for (String name : props.stringPropertyNames()) {
                result.put(name.toLowerCase(), props.getProperty(name));
            }

            return result;
        }
    }

    public static void watchInstance(final String bizName, final IZkDataListener listener) {
        final String path = "/xpower/dbn/" + bizName;
        ConfigCenter.getInstance().subscribeDataChanges(path, listener);
    }
}

实际应用

最后在MyBatis项目中, 替换原有MainDataSource代码为:



    @Primary
    @Bean(name = "mainDataSource")
    public DataSource mainDataSource() throws Exception {
        return SimpleDBNDataSourceFactory.getInstance().getDataSource("cavedemo");
    }

运行项目, 发现可以连上数据库, 并且不重启项目的情况下, 动态修改数据库配置, 能自动重连.

项目代码:

https://github.com/cnscud/xpower/tree/main/xpower-main/src/main/java/com/cnscud/xpower/dbn

其中用到的 ConfigCenter 也在这个项目里, 也可以自己实现, 就可以脱离本项目了.

本文来自博客园,作者:飞云~风之谷,转载请注明原文链接:Https://www.cnblogs.com/cnscud/p/15103859.html

到此这篇关于MyBatis使用Zookeeper保存数据库的配置,可动态刷新的文章就介绍到这了,更多相关MyBatis使用Zookeeper保存数据库的配置,可动态刷新内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: MyBatis使用Zookeeper保存数据库的配置可动态刷新的实现代码

本文链接: https://www.lsjlt.com/news/131955.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作