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ù)據(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
到此這篇關于SpringBoot集成nacos動態(tài)刷新數(shù)據(jù)源的實現(xiàn)示例的文章就介紹到這了,更多相關SpringBoot nacos動態(tài)刷新數(shù)據(jù)源內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
1. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法2. WMLScript的語法基礎3. ASP中解決“對象關閉時,不允許操作。”的詭異問題……4. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯誤頁的問題5. html小技巧之td,div標簽里內(nèi)容不換行6. xml中的空格之完全解說7. XML入門的常見問題(四)8. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁9. ASP中if語句、select 、while循環(huán)的使用方法10. ASP動態(tài)網(wǎng)頁制作技術經(jīng)驗分享
