nacos只支持mysql的原因分析
什么是Nacos
英文全稱Dynamic Naming and Configuration Service,Na為naming/nameServer即注冊中心,co為configuration即注冊中心,service是指該注冊/配置中心都是以服務(wù)為核心。服務(wù)在nacos是一等公民
沒看源碼之前,覺得很離譜,為啥只能限制數(shù)據(jù)庫為mysql,按道理來說,nacos用了JdbcTemplate,可以適配很多數(shù)據(jù)庫才是
最近看了nacos的源碼,發(fā)現(xiàn)其中有很多硬編碼,才明白原因
nacos的數(shù)據(jù)源獲取都是通過com.alibaba.nacos.config.server.service.datasource.DynamicDataSource來獲取的
在獲取數(shù)據(jù)源時,根據(jù)配置判斷你到底是使用內(nèi)置的本地數(shù)據(jù)庫還是外部的數(shù)據(jù)庫(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")來判斷你到底是不是standalone模式
// standalone模式,使用內(nèi)置數(shù)據(jù)庫
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ù)庫
// 這個可以在com.alibaba.nacos.config.server.utils.PropertyUtil#loadSetting中看到
// setUseExternalDB("mysql".equalsIgnoreCase(getString("spring.datasource.platform", "")));
// 好家伙,直接判斷配置的是不是mysql,是mysql那就是外部數(shù)據(jù)庫,進(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對象,賦值操作
// 因為外面是直接new出來的,需要對屬性根據(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");
// 可以配置多個數(shù)據(jù)庫
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一堆,這個針對所有的數(shù)據(jù)源都適用
DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(environment);
// 為每一個數(shù)據(jù)源進(jìn)行單獨的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;
}這個整體還行,但是為啥JDBC_DRIVER_NAME是硬編碼呢,代碼中清晰看到
private static final String JDBC_DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
到這已經(jīng)一目了然,代碼中硬編碼了mysql,driver也沒法改,所以根本沒法更換數(shù)據(jù)庫驅(qū)動,有點騷,而且com.mysql.cj.jdbc.Driver是mysql8的驅(qū)動,對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ù)庫工作量還是非常大的
到此這篇關(guān)于為什么nacos只支持mysql的文章就介紹到這了,更多相關(guān)nacos只支持mysql內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一文詳解如何在MySQL中創(chuàng)建函數(shù)
這篇文章主要為大家介紹了一文詳解如何在MySQL中創(chuàng)建函數(shù),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05
MySQL中create table as 與like的區(qū)別分析
這篇文章主要介紹了MySQL中create table as 與like的區(qū)別,結(jié)合實例分析了二者在使用中的具體區(qū)別與主要用途,需要的朋友可以參考下2016-01-01
MySQL數(shù)據(jù)庫優(yōu)化的六種方式總結(jié)
關(guān)于數(shù)據(jù)庫優(yōu)化,網(wǎng)上有不少資料和方法,但是不少質(zhì)量參差不齊,所以下面這篇文章主要給大家介紹了關(guān)于MySQL數(shù)據(jù)庫優(yōu)化的六種方式,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-01-01
解析SQL語句中Replace INTO與INSERT INTO的不同之處
本篇文章是對SQL語句中Replace INTO與INSERT INTO的不同之處進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06
MySQL報錯Lost connection to MySQL server&n
在確保網(wǎng)絡(luò)沒有問題的情況下,服務(wù)器正常運行一段時間后,數(shù)據(jù)庫拋出了異常"Lost connection to MySQL server during query",本文將給大家介紹MySQL報錯Lost connection to MySQL server during query的解決方案,需要的朋友可以參考下2024-01-01

