SpringBoot集成nacos動態(tài)刷新數(shù)據(jù)源的實現(xiàn)示例
因為項目需要,需要在項目運行過程中能夠動態(tài)修改數(shù)據(jù)源(即:數(shù)據(jù)源的熱更新)。這里以com.alibaba.druid.pool.DruidDataSource數(shù)據(jù)源為例
第一步:重寫DruidAbstractDataSource類這里為什么要重寫這個類:因為DruidDataSource數(shù)據(jù)源在初始化后,就不允許再重新設(shè)置數(shù)據(jù)庫的url和userName
public void setUrl(String jdbcUrl) { if (StringUtils.equals(this.jdbcUrl, jdbcUrl)) { return; } // 重寫的時候,需要將這個判斷注釋掉,否則會報錯 // if (inited) { // throw new UnsupportedOperationException(); // } if (jdbcUrl != null) { jdbcUrl = jdbcUrl.trim(); } this.jdbcUrl = jdbcUrl; // if (jdbcUrl.startsWith(ConfigFilter.URL_PREFIX)) { // this.filters.add(new ConfigFilter()); // } } public void setUsername(String username) { if (StringUtils.equals(this.username, username)) { return; }// 重寫的時候,需要將這個判斷注釋掉,否則會報錯 // if (inited) { // throw new UnsupportedOperationException(); // } this.username = username; }
重寫的時候包路徑不能變,只有這樣類加載的時候才會優(yōu)先加載重寫后的類
package com.mp.demo.config;import com.alibaba.druid.pool.DruidDataSource;import lombok.Data;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Value;import org.springframework.cloud.context.config.annotation.RefreshScope;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Slf4j@Configuration@RefreshScope@Datapublic class DruidConfiguration{ @Value('${spring.datasource.url}') private String dbUrl; @Value('${spring.datasource.username}') private String username; @Value('${spring.datasource.password}') private String password; @Value('${spring.datasource.driver-class-name}') private String driverClassName; @Bean @RefreshScope public DruidDataSource dataSource() { DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(this.dbUrl); datasource.setUsername(username); datasource.setPassword(password); datasource.setDriverClassName(driverClassName); return datasource; }}
這里要注意增加@RefreshScope注解
第三步:手動刷新數(shù)據(jù)源@GetMapping('/refresh') public String refresh() throws SQLException { DruidDataSource master = SpringUtils.getBean('dataSource'); master.setUrl(druidConfiguration.getDbUrl()); master.setUsername(druidConfiguration.getUsername()); master.setPassword(druidConfiguration.getPassword()); master.setDriverClassName(druidConfiguration.getDriverClassName()); master.restart(); return userName + '<>' + jdbcUrl+'----------'+druidConfiguration.getDbUrl(); }
源碼地址:https://gitee.com/jackson_hou/RefreshDataSource.git
到此這篇關(guān)于SpringBoot集成nacos動態(tài)刷新數(shù)據(jù)源的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)SpringBoot nacos動態(tài)刷新數(shù)據(jù)源內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
