nacos只支持mysql的原因分析

 更新时间:2022年01月19日 14:17:23   作者:骑白马走三关  
nacos的数据源获取都是通过com.alibaba.nacos.config.server.service.datasource.DynamicDataSource来获取的,在获取数据源时,根据配置判断你到底是使用内置的本地数据库还是外部的数据库(mysql),本文给大家详细介绍,需要的朋友可以参考下

什么是Nacos

英文全称Dynamic Naming and Configuration Service,Na为naming/nameServer即注册中心,co为configuration即注册中心,service是指该注册/配置中心都是以服务为核心。服务在nacos是一等公民

没看源码之前,觉得很离谱,为啥只能限制数据库为mysql,按道理来说,nacos用了JdbcTemplate,可以适配很多数据库才是

最近看了nacos的源码,发现其中有很多硬编码,才明白原因

nacos的数据源获取都是通过com.alibaba.nacos.config.server.service.datasource.DynamicDataSource来获取的

在获取数据源时,根据配置判断你到底是使用内置的本地数据库还是外部的数据库(mysql)

public synchronized DataSourceService getDataSource() {
    try {

        // Embedded storage is used by default in stand-alone mode
        // In cluster mode, external databases are used by default
        // 根据System.getProperty("nacos.standalone")来判断你到底是不是standalone模式
        // standalone模式,使用内置数据库
        if (PropertyUtil.isEmbeddedStorage()) {
            if (localDataSourceService == null) {
                localDataSourceService = new LocalDataSourceServiceImpl();
                localDataSourceService.init();
            }
            return localDataSourceService;
        } else {
            // 如果不是standalone,直接创建外部的数据源
            if (basicDataSourceService == null) {
                basicDataSourceService = new ExternalDataSourceServiceImpl();
                basicDataSourceService.init();
            }
            return basicDataSourceService;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

外部数据源com.alibaba.nacos.config.server.service.datasource.ExternalDataSourceServiceImpl.init()

@Override
public void init() {
    queryTimeout = ConvertUtils.toInt(System.getProperty("QUERYTIMEOUT"), 3);
    jt = new JdbcTemplate();
    // Set the maximum number of records to prevent memory expansion
    jt.setMaxRows(50000);
    jt.setQueryTimeout(queryTimeout);
    testMasterJT = new JdbcTemplate();
    testMasterJT.setQueryTimeout(queryTimeout);
    testMasterWritableJT = new JdbcTemplate();
    // Prevent the login interface from being too long because the main library is not available
    testMasterWritableJT.setQueryTimeout(1);
    //  Database health check
    testJtList = new ArrayList<JdbcTemplate>();
    isHealthList = new ArrayList<Boolean>();
    tm = new DataSourceTransactionManager();
    tjt = new TransactionTemplate(tm);
    // Transaction timeout needs to be distinguished from ordinary operations.
    tjt.setTimeout(TRANSACTION_QUERY_TIMEOUT);
    // 判断到底是是不是用外部数据库
    // 这个可以在com.alibaba.nacos.config.server.utils.PropertyUtil#loadSetting中看到
    // setUseExternalDB("mysql".equalsIgnoreCase(getString("spring.datasource.platform", "")));
    // 好家伙,直接判断配置的是不是mysql,是mysql那就是外部数据库,进行reload,不是,那就不管了
    if (PropertyUtil.isUseExternalDB()) {
        try {
            reload();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(DB_LOAD_ERROR_MSG);
        }
        if (this.dataSourceList.size() > DB_MASTER_SELECT_THRESHOLD) {
            ConfigExecutor.scheduleConfigTask(new SelectMasterTask(), 10, 10, TimeUnit.SECONDS);
        }
        ConfigExecutor.scheduleConfigTask(new CheckDbHealthTask(), 10, 10, TimeUnit.SECONDS);
    }
}

在com.alibaba.nacos.config.server.service.datasource.ExternalDataSourceServiceImpl#reload中,我们可以看到

@Override
public synchronized void reload() throws IOException {
    try {
        // 根据配置文件,构建数据源集合
        dataSourceList = new ExternalDataSourceProperties()
            .build(EnvUtil.getEnvironment(), (dataSource) -> {
                JdbcTemplate jdbcTemplate = new JdbcTemplate();
                jdbcTemplate.setQueryTimeout(queryTimeout);
                jdbcTemplate.setDataSource(dataSource);
                testJtList.add(jdbcTemplate);
                isHealthList.add(Boolean.TRUE);
            });
        new SelectMasterTask().run();
        new CheckDbHealthTask().run();
    } catch (RuntimeException e) {
        FATAL_LOG.error(DB_LOAD_ERROR_MSG, e);
        throw new IOException(e);
    }
}

在com.alibaba.nacos.config.server.service.datasource.ExternalDataSourceProperties#build中

List<HikariDataSource> build(Environment environment, Callback<HikariDataSource> callback) {
    List<HikariDataSource> dataSources = new ArrayList<>();
    // 把胚子信息绑定到当前的ExternalDataSourceProperties对象,赋值操作
    // 因为外面是直接new出来的,需要对属性根据文件进行赋值
    Binder.get(environment).bind("db", Bindable.ofInstance(this));
    Preconditions.checkArgument(Objects.nonNull(num), "db.num is null");
    Preconditions.checkArgument(CollectionUtils.isNotEmpty(user), "db.user or db.user.[index] is null");
    Preconditions.checkArgument(CollectionUtils.isNotEmpty(password), "db.password or db.password.[index] is null");
    // 可以配置多个数据库
    for (int index = 0; index < num; index++) {
        int currentSize = index + 1;
        Preconditions.checkArgument(url.size() >= currentSize, "db.url.%s is null", index);
        // 拿到spring.datasource.xxx一堆,这个针对所有的数据源都适用
        DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(environment);
        // 为每一个数据源进行单独的url,user,password进行替换
        poolProperties.setDriverClassName(JDBC_DRIVER_NAME);
        poolProperties.setJdbcUrl(url.get(index).trim());
        poolProperties.setUsername(getOrDefault(user, index, user.get(0)).trim());
        poolProperties.setPassword(getOrDefault(password, index, password.get(0)).trim());
        HikariDataSource ds = poolProperties.getDataSource();
        ds.setConnectionTestQuery(TEST_QUERY);
        dataSources.add(ds);
        callback.accept(ds);
    }
    Preconditions.checkArgument(CollectionUtils.isNotEmpty(dataSources), "no datasource available");
    return dataSources;
}

这个整体还行,但是为啥JDBC_DRIVER_NAME是硬编码呢,代码中清晰看到

private static final String JDBC_DRIVER_NAME = "com.mysql.cj.jdbc.Driver";

到这已经一目了然,代码中硬编码了mysql,driver也没法改,所以根本没法更换数据库驱动,有点骚,而且com.mysql.cj.jdbc.Driver是mysql8的驱动,对mysql版本是有要求的

再看其他部分,也可以发现大量的硬编码,例如com.alibaba.nacos.config.server.auth.ExternalUserPersistServiceImpl

public class ExternalUserPersistServiceImpl implements UserPersistService {
    
    @Autowired
    private ExternalStoragePersistServiceImpl persistService;
    
    private JdbcTemplate jt;
    
    @PostConstruct
    protected void init() {
        jt = persistService.getJdbcTemplate();
    }
    
    /**
     * Execute create user operation.
     *
     * @param username username string value.
     * @param password password string value.
     */
    public void createUser(String username, String password) {
        String sql = "INSERT into users (username, password, enabled) VALUES (?, ?, ?)";
        
        try {
            jt.update(sql, username, password, true);
        } catch (CannotGetJdbcConnectionException e) {
            LogUtil.FATAL_LOG.error("[db-error] " + e.toString(), e);
            throw e;
        }
    }
    
    /**
     * Execute delete user operation.
     *
     * @param username username string value.
     */
    public void deleteUser(String username) {
        String sql = "DELETE from users WHERE username=?";
        try {
            jt.update(sql, username);
        } catch (CannotGetJdbcConnectionException e) {
            LogUtil.FATAL_LOG.error("[db-error] " + e.toString(), e);
            throw e;
        }
    }
    
    /**
     * Execute update user password operation.
     *
     * @param username username string value.
     * @param password password string value.
     */
    public void updateUserPassword(String username, String password) {
        try {
            jt.update("UPDATE users SET password = ? WHERE username=?", password, username);
        } catch (CannotGetJdbcConnectionException e) {
            LogUtil.FATAL_LOG.error("[db-error] " + e.toString(), e);
            throw e;
        }
    }
    
    /**
     * Execute find user by username operation.
     *
     * @param username username string value.
     * @return User model.
     */
    public User findUserByUsername(String username) {
        String sql = "SELECT username,password FROM users WHERE username=? ";
        try {
            return this.jt.queryForObject(sql, new Object[] {username}, USER_ROW_MAPPER);
        } catch (CannotGetJdbcConnectionException e) {
            LogUtil.FATAL_LOG.error("[db-error] " + e.toString(), e);
            throw e;
        } catch (EmptyResultDataAccessException e) {
            return null;
        } catch (Exception e) {
            LogUtil.FATAL_LOG.error("[db-other-error]" + e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
    
    public Page<User> getUsers(int pageNo, int pageSize) {
        
        PaginationHelper<User> helper = persistService.createPaginationHelper();
        
        String sqlCountRows = "select count(*) from users where ";
        String sqlFetchRows = "select username,password from users where ";
        
        String where = " 1=1 ";
        
        try {
            Page<User> pageInfo = helper
                    .fetchPage(sqlCountRows + where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
                            pageSize, USER_ROW_MAPPER);
            if (pageInfo == null) {
                pageInfo = new Page<>();
                pageInfo.setTotalCount(0);
                pageInfo.setPageItems(new ArrayList<>());
            }
            return pageInfo;
        } catch (CannotGetJdbcConnectionException e) {
            LogUtil.FATAL_LOG.error("[db-error] " + e.toString(), e);
            throw e;
        }
    }
    @Override
    public List<String> findUserLikeUsername(String username) {
        String sql = "SELECT username FROM users WHERE username like '%' ? '%'";
        List<String> users = this.jt.queryForList(sql, new String[]{username}, String.class);
        return users;
    }
}

几乎所有的sql都是硬编码....所以要改造成其他数据库工作量还是非常大的

到此这篇关于为什么nacos只支持mysql的文章就介绍到这了,更多相关nacos只支持mysql内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 详解Mysql查询条件中字符串尾部有空格也能匹配上的问题

    详解Mysql查询条件中字符串尾部有空格也能匹配上的问题

    在本篇文章里小编给大家整理的是关于详解Mysql查询条件中字符串尾部有空格也能匹配上的问题,需要的朋友们可以参考下
    2020-02-02
  • MySQL统计时间差的平均值方式

    MySQL统计时间差的平均值方式

    这篇文章主要介绍了MySQL统计时间差的平均值方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • 一文详解如何在MySQL中创建函数

    一文详解如何在MySQL中创建函数

    这篇文章主要为大家介绍了一文详解如何在MySQL中创建函数,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-05-05
  • MySQL中create table as 与like的区别分析

    MySQL中create table as 与like的区别分析

    这篇文章主要介绍了MySQL中create table as 与like的区别,结合实例分析了二者在使用中的具体区别与主要用途,需要的朋友可以参考下
    2016-01-01
  • mysql如何设置不区分大小写

    mysql如何设置不区分大小写

    在本篇文章里小编给大家整理了关于mysql设置不区分大小写的方法,需要的朋友们跟着学习下。
    2020-06-06
  • mysql Myisamchk小工具使用手册

    mysql Myisamchk小工具使用手册

    Myisamchk是MyISAM表维护的一个非常实用的工具。可以使用myisamchk实用程序来获得有关数据库表的信息或检查、修复、优化他们。myisamchk适用MyISAM表(对应.MYI和.MYD文件的表)。
    2008-10-10
  • MySQL数据库优化的六种方式总结

    MySQL数据库优化的六种方式总结

    关于数据库优化,网上有不少资料和方法,但是不少质量参差不齐,所以下面这篇文章主要给大家介绍了关于MySQL数据库优化的六种方式,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-01-01
  • 解析SQL语句中Replace INTO与INSERT INTO的不同之处

    解析SQL语句中Replace INTO与INSERT INTO的不同之处

    本篇文章是对SQL语句中Replace INTO与INSERT INTO的不同之处进行了详细的分析介绍,需要的朋友参考下
    2013-06-06
  • ubuntu下设置mysql自动备份的例子

    ubuntu下设置mysql自动备份的例子

    ubuntu下设置mysql自动备份的例子,供大家学习参考
    2013-01-01
  • MySQL报错Lost connection to MySQL server during query的解决方案

    MySQL报错Lost connection to MySQL server&n

    在确保网络没有问题的情况下,服务器正常运行一段时间后,数据库抛出了异常"Lost connection to MySQL server during query",本文将给大家介绍MySQL报错Lost connection to MySQL server during query的解决方案,需要的朋友可以参考下
    2024-01-01

最新评论