詳解spring cloud config實現datasource的熱部署,clouddatasource

來源:互聯網
上載者:User

詳解spring cloud config實現datasource的熱部署,clouddatasource

關於spring cloud config的基本使用,前面的部落格中已經說過了,如果不瞭解的話,請先看以前的部落格

spring cloud config整合gitlab搭建分布式的配置中心

spring cloud config分布式配置中心的高可用

今天,我們的重點是如何?資料來源的熱部署。

1、在用戶端配置資料來源

@RefreshScope @Configuration// 配置資料來源 public class DataSourceConfigure {    @Bean   @RefreshScope// 重新整理設定檔   @ConfigurationProperties(prefix="spring.datasource") // 資料來源的自動設定的首碼   public DataSource dataSource(){     return DataSourceBuilder.create().build();   } } 

通過上面的幾個步驟,就可以實現在gitlab上修改設定檔,重新整理後,伺服器不用重啟,新的資料來源就會生效。

2、自訂資料來源的熱部署

當我們使用spring boot整合druid,我們需要手動來配置資料來源,代碼如下:

package com.chhliu.springcloud.config;  import java.sql.SQLException; import javax.sql.DataSource; 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; import org.springframework.context.annotation.Primary;  import com.alibaba.druid.pool.DruidDataSource; import lombok.extern.slf4j.Slf4j;  /**  *  * 描述:如果不使用代碼手動初始化DataSource的話,監控介面的SQL監控會沒有資料("是spring boot的bug???")  * @author chhliu  * 建立時間:2017年2月9日 下午7:33:08  * @version 1.2.0  */ @Slf4j @Configuration @RefreshScope public 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.driverClassName}")   private String driverClassName;   @Value("${spring.datasource.initialSize}")   private int initialSize;   @Value("${spring.datasource.minIdle}")   private int minIdle;   @Value("${spring.datasource.maxActive}")   private int maxActive;   @Value("${spring.datasource.maxWait}")   private int maxWait;   @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")   private int timeBetweenEvictionRunsMillis;   @Value("${spring.datasource.minEvictableIdleTimeMillis}")   private int minEvictableIdleTimeMillis;   @Value("${spring.datasource.validationQuery}")   private String validationQuery;   @Value("${spring.datasource.testWhileIdle}")   private boolean testWhileIdle;   @Value("${spring.datasource.testOnBorrow}")   private boolean testOnBorrow;   @Value("${spring.datasource.testOnReturn}")   private boolean testOnReturn;   @Value("${spring.datasource.poolPreparedStatements}")   private boolean poolPreparedStatements;   @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")   private int maxPoolPreparedStatementPerConnectionSize;   @Value("${spring.datasource.filters}")   private String filters;   @Value("${spring.datasource.connectionProperties}")   private String connectionProperties;   @Value("${spring.datasource.useGlobalDataSourceStat}")   private boolean useGlobalDataSourceStat;    @Bean   //聲明其為Bean執行個體   @Primary //在同樣的DataSource中,首先使用被標註的DataSource   @RefreshScope   public DataSource dataSource(){     DruidDataSource datasource = new DruidDataSource();     datasource.setUrl(this.dbUrl);     datasource.setUsername(username);     datasource.setPassword(password);     datasource.setDriverClassName(driverClassName);      //configuration     datasource.setInitialSize(initialSize);     datasource.setMinIdle(minIdle);     datasource.setMaxActive(maxActive);     datasource.setMaxWait(maxWait);     datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);     datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);     datasource.setValidationQuery(validationQuery);     datasource.setTestWhileIdle(testWhileIdle);     datasource.setTestOnBorrow(testOnBorrow);     datasource.setTestOnReturn(testOnReturn);     datasource.setPoolPreparedStatements(poolPreparedStatements);     datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);     datasource.setUseGlobalDataSourceStat(useGlobalDataSourceStat);     try {       datasource.setFilters(filters);     } catch (SQLException e) {       log.error("druid configuration initialization filter: "+ e);     }     datasource.setConnectionProperties(connectionProperties);     return datasource;   } } 

通過上面的樣本,也可以實現資料來源的動態重新整理。接下來,我們就來看看,spring cloud config是怎麼來實現資料來源的熱部署的。

從前面的部落格中,我們不難發現,要想實現動態重新整理,關鍵點就在post refresh的請求上,那我們就從重新整理設定檔開始。
當我們post重新整理請求的時候,這個請求會被actuator模組攔截,這點從啟動的記錄檔中就可以看出

複製代碼 代碼如下:
Mapped "{[/refresh || /refresh.json],methods=[POST]}" onto public java.lang.Object org.springframework.cloud.endpoint.GenericPostableMvcEndpoint.invoke() 

接下來,我們就來看actuator定義的EndPoint,然後我們就找到了RefreshEndpoint這個類,該類的源碼如下:

@ConfigurationProperties(prefix = "endpoints.refresh", ignoreUnknownFields = false) @ManagedResource public class RefreshEndpoint extends AbstractEndpoint<Collection<String>> {    private ContextRefresher contextRefresher;    public RefreshEndpoint(ContextRefresher contextRefresher) {     super("refresh");     this.contextRefresher = contextRefresher;   }    @ManagedOperation   public String[] refresh() {     Set<String> keys = contextRefresher.refresh();     return keys.toArray(new String[keys.size()]);   }    @Override   public Collection<String> invoke() {     return Arrays.asList(refresh());   }  } 

從上面的源碼,我們可以看到,重點在ContextRefresher這個類上,由於這個類太長了,下面把這個類的部分源碼貼出來:

private RefreshScope scope;    public ContextRefresher(ConfigurableApplicationContext context, RefreshScope scope) {     this.context = context;     this.scope = scope;   }    public synchronized Set<String> refresh() {     Map<String, Object> before = extract(         this.context.getEnvironment().getPropertySources());// 1、before,載入提取設定檔     addConfigFilesToEnvironment();// 2、將設定檔載入到環境中     Set<String> keys = changes(before,         extract(this.context.getEnvironment().getPropertySources())).keySet();// 3、替換原來環境變數中的值     this.context.publishEvent(new EnvironmentChangeEvent(keys));// 4、發布變更事件,     this.scope.refreshAll();     return keys;   } 

從上面的代碼不難看出,重點經曆了4個步驟,上面代碼中已標註。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.