亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

nacos只支持mysql的原因分析

 更新時(shí)間:2022年01月19日 14:17:23   作者:騎白馬走三關(guān)  
nacos的數(shù)據(jù)源獲取都是通過(guò)com.alibaba.nacos.config.server.service.datasource.DynamicDataSource來(lái)獲取的,在獲取數(shù)據(jù)源時(shí),根據(jù)配置判斷你到底是使用內(nèi)置的本地?cái)?shù)據(jù)庫(kù)還是外部的數(shù)據(jù)庫(kù)(mysql),本文給大家詳細(xì)介紹,需要的朋友可以參考下

什么是Nacos

英文全稱(chēng)Dynamic Naming and Configuration Service,Na為naming/nameServer即注冊(cè)中心,co為configuration即注冊(cè)中心,service是指該注冊(cè)/配置中心都是以服務(wù)為核心。服務(wù)在nacos是一等公民

沒(méi)看源碼之前,覺(jué)得很離譜,為啥只能限制數(shù)據(jù)庫(kù)為mysql,按道理來(lái)說(shuō),nacos用了JdbcTemplate,可以適配很多數(shù)據(jù)庫(kù)才是

最近看了nacos的源碼,發(fā)現(xiàn)其中有很多硬編碼,才明白原因

nacos的數(shù)據(jù)源獲取都是通過(guò)com.alibaba.nacos.config.server.service.datasource.DynamicDataSource來(lái)獲取的

在獲取數(shù)據(jù)源時(shí),根據(jù)配置判斷你到底是使用內(nèi)置的本地?cái)?shù)據(jù)庫(kù)還是外部的數(shù)據(jù)庫(kù)(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
        // 根據(jù)System.getProperty("nacos.standalone")來(lái)判斷你到底是不是standalone模式
        // standalone模式,使用內(nèi)置數(shù)據(jù)庫(kù)
        if (PropertyUtil.isEmbeddedStorage()) {
            if (localDataSourceService == null) {
                localDataSourceService = new LocalDataSourceServiceImpl();
                localDataSourceService.init();
            }
            return localDataSourceService;
        } else {
            // 如果不是standalone,直接創(chuàng)建外部的數(shù)據(jù)源
            if (basicDataSourceService == null) {
                basicDataSourceService = new ExternalDataSourceServiceImpl();
                basicDataSourceService.init();
            }
            return basicDataSourceService;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

外部數(shù)據(jù)源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);
    // 判斷到底是是不是用外部數(shù)據(jù)庫(kù)
    // 這個(gè)可以在com.alibaba.nacos.config.server.utils.PropertyUtil#loadSetting中看到
    // setUseExternalDB("mysql".equalsIgnoreCase(getString("spring.datasource.platform", "")));
    // 好家伙,直接判斷配置的是不是mysql,是mysql那就是外部數(shù)據(jù)庫(kù),進(jìn)行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 {
        // 根據(jù)配置文件,構(gòu)建數(shù)據(jù)源集合
        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<>();
    // 把胚子信息綁定到當(dāng)前的ExternalDataSourceProperties對(duì)象,賦值操作
    // 因?yàn)橥饷媸侵苯觧ew出來(lái)的,需要對(duì)屬性根據(jù)文件進(jìn)行賦值
    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");
    // 可以配置多個(gè)數(shù)據(jù)庫(kù)
    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一堆,這個(gè)針對(duì)所有的數(shù)據(jù)源都適用
        DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(environment);
        // 為每一個(gè)數(shù)據(jù)源進(jìn)行單獨(dú)的url,user,password進(jìn)行替換
        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;
}

這個(gè)整體還行,但是為啥JDBC_DRIVER_NAME是硬編碼呢,代碼中清晰看到

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

到這已經(jīng)一目了然,代碼中硬編碼了mysql,driver也沒(méi)法改,所以根本沒(méi)法更換數(shù)據(jù)庫(kù)驅(qū)動(dòng),有點(diǎn)騷,而且com.mysql.cj.jdbc.Driver是mysql8的驅(qū)動(dòng),對(duì)mysql版本是有要求的

再看其他部分,也可以發(fā)現(xiàn)大量的硬編碼,例如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都是硬編碼....所以要改造成其他數(shù)據(jù)庫(kù)工作量還是非常大的

到此這篇關(guān)于為什么nacos只支持mysql的文章就介紹到這了,更多相關(guān)nacos只支持mysql內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論