Spring boot 有沒有辦法在運行時創建指向不同 MySQL 資料庫的Jdbctemplate?
運行時我確實擁有所有必需的資訊。
所有客戶端的資料庫結構相同,但實體不同。
我還嘗試了如何在運行時創建多個指向不同 Mysql 資料庫的 Jdbctemplate bean? 但無法找到任何解決方案。
uj5u.com熱心網友回復:
我想這可以這樣做:
@Component
public class JdbcTemplateProvider {
private final Map<String, DataSource> databaseNameToDataSourceMap;
private final JdbcProperties properties;
public JdbcTemplateProvider(List<DataSource> dataSources, JdbcProperties properties) {
this.databaseNameToDataSourceMap = this.buildDatabaseToDataSourceMap(dataSources);
this.properties = properties;
}
public JdbcTemplate byDatabaseName(String database) {
DataSource dataSource = this.databaseNameToDataSourceMap.get(database);
return buildJdbcTemplate(dataSource);
}
private Map<String, DataSource> buildDatabaseToDataSourceMap(List<DataSource> dataSources) {
return new ConcurrentHashMap<>();
}
private JdbcTemplate buildJdbcTemplate(DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
JdbcProperties.Template template = properties.getTemplate();
jdbcTemplate.setFetchSize(template.getFetchSize());
jdbcTemplate.setMaxRows(template.getMaxRows());
if (template.getQueryTimeout() != null) {
jdbcTemplate.setQueryTimeout((int) template.getQueryTimeout().getSeconds());
}
return jdbcTemplate;
}
}
如果這個問題是 Spring Boot 是否可以本地處理這個問題,據我所知,可能沒有任何內置的解決方案。
org.springframework.boot.autoconfigure.jdbc.JdbcProperties讀取帶有前綴的屬性值spring.jdbc。如果它在您的類路徑中可用,這將能夠根據配置配置新構建JdbcTemplate的實體。
您將構建自己的邏輯來構建資料庫名稱到資料源的映射。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/444866.html
標籤:mysql 弹簧靴 spring-jdbc jdbc模板
上一篇:從Angular向Java發送multipartFile
下一篇:無法將java.lang.String轉換為com.fasterxml.jackson.databind.MapperFeature
