溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Config中怎么實(shí)現(xiàn)配置熱刷新

發(fā)布時(shí)間:2021-06-26 14:08:17 來源:億速云 閱讀:678 作者:Leah 欄目:web開發(fā)

Config中怎么實(shí)現(xiàn)配置熱刷新,針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。

問題1. 如何實(shí)現(xiàn)配置熱刷新重點(diǎn) Nacos原理:

  • 1.在需要熱刷新的Bean上使用Spring Cloud原生注解 @RefreshScope

  • 2.當(dāng)有配置更新的時(shí)候調(diào)用contextRefresher.refresh()

代碼如下:

@RestController @RequestMapping("/config") @RefreshScope // 重點(diǎn) public class ConfigController {     @Value("${laker.name}") // 待刷新的屬性     private String lakerName;     @RequestMapping("/get")     public String get() {         return lakerName;     }  ... }

1. @RefreshScope原理

@RefreshScope位于spring-cloud-context,源碼注釋如下:

可將@Bean定義放入org.springframework.cloud.context.scope.refresh.RefreshScope中。用這種方式注解的Bean可以在運(yùn)行時(shí)刷新,并且使用它們的任何組件都將在下一個(gè)方法調(diào)用前獲得一個(gè)新實(shí)例,該實(shí)例將完全初始化并注入所有依賴項(xiàng)。

要清楚RefreshScope,先要了解Scope

Scope(org.springframework.beans.factory.config.Scope)是Spring  2.0開始就有的核心的概念

RefreshScope(org.springframework.cloud.context.scope.refresh),  即@Scope("refresh")是spring cloud提供的一種特殊的scope實(shí)現(xiàn),用來實(shí)現(xiàn)配置、實(shí)例熱加載。

類似的有:

  • RequestScope:是從當(dāng)前web request中獲取實(shí)例的實(shí)例

  • SessionScope:是從Session中獲取實(shí)例的實(shí)例

  • ThreadScope:是從ThreadLocal中獲取的實(shí)例

RefreshScope是從內(nèi)建緩存中獲取的。

2. ContextRefresher.refresh()

當(dāng)有配置更新的時(shí)候,觸發(fā)ContextRefresher.refresh

RefreshScope 刷新過程

入口在ContextRefresher.refresh

public synchronized Set<String> refresh() { ①  Map<String, Object> before = extract(this.context.getEnvironment().getPropertySources()); ②  updateEnvironment(); ④  Set<String> keys = changes(before, ③extract(this.context.getEnvironment().getPropertySources())).keySet(); ⑤  this.context.publishEvent(new EnvironmentChangeEvent(this.context, keys)); ⑥       this.scope.refreshAll(); }

①提取標(biāo)準(zhǔn)參數(shù)(SYSTEM,JNDI,SERVLET)之外所有參數(shù)變量

②把原來的Environment里的參數(shù)放到一個(gè)新建的Spring  Context容器下重新加載,完事之后關(guān)閉新容器(重點(diǎn):可以去debug跟蹤下,實(shí)際上是重啟了個(gè)SpringApplication)

③提起更新過的參數(shù)(排除標(biāo)準(zhǔn)參數(shù))

④比較出變更項(xiàng)

⑤發(fā)布環(huán)境變更事件

⑥RefreshScope用新的環(huán)境參數(shù)重新生成Bean,重新生成的過程很簡單,清除refreshscope緩存幷銷毀Bean,下次就會(huì)重新從BeanFactory獲取一個(gè)新的實(shí)例(該實(shí)例使用新的配置)

3. RefreshScope.refreshAll()

RefreshScope.refreshAll方法實(shí)現(xiàn),即上面的第⑥步調(diào)用:

public void refreshAll() {   super.destroy();   this.context.publishEvent(new RefreshScopeRefreshedEvent()); }

RefreshScope類中有一個(gè)成員變量 cache,用于緩存所有已經(jīng)生成的 Bean,在調(diào)用 get  方法時(shí)嘗試從緩存加載,如果沒有的話就生成一個(gè)新對(duì)象放入緩存,并通過 getBean 初始化其對(duì)應(yīng)的 Bean:

public Object get(String name, ObjectFactory<?> objectFactory) {  BeanLifecycleWrapper value = this.cache.put(name, new BeanLifecycleWrapper(name, objectFactory));  this.locks.putIfAbsent(name, new ReentrantReadWriteLock());  try {   return value.getBean();  }  catch (RuntimeException e) {   this.errors.put(name, e);   throw e;  } }

所以在銷毀時(shí)只需要將整個(gè)緩存清空,下次獲取對(duì)象時(shí)自然就可以重新生成新的對(duì)象,也就自然綁定了新的屬性:

public void destroy() {  List<Throwable> errors = new ArrayList<Throwable>();  Collection<BeanLifecycleWrapper> wrappers = this.cache.clear();  for (BeanLifecycleWrapper wrapper : wrappers) {   try {    Lock lock = this.locks.get(wrapper.getName()).writeLock();    lock.lock();    try {     wrapper.destroy();    }    finally {     lock.unlock();    }   }   catch (RuntimeException e) {    errors.add(e);   }  }  if (!errors.isEmpty()) {   throw wrapIfNecessary(errors.get(0));  }  this.errors.clear(); }

清空緩存后,下次訪問對(duì)象時(shí)就會(huì)重新創(chuàng)建新的對(duì)象并放入緩存了。

而在清空緩存后,它還會(huì)發(fā)出一個(gè) RefreshScopeRefreshedEvent 事件,在某些 Spring Cloud  的組件中會(huì)監(jiān)聽這個(gè)事件并作出一些反饋。

4. 模擬造輪子

這里我們就可以模擬造個(gè)熱更新的輪子了;

代碼以及配置如下:

  • 項(xiàng)目依賴spring-cloud-context

<dependency>   <groupId>org.springframework.cloud</groupId>   <artifactId>spring-cloud-context</artifactId> </dependency>
  • 配置bean

@Component @RefreshScope public class User {     @Value("${laker.name}")     private String name;     ... }
  • 刷新接口以及查看接口

@RestController @RequestMapping("/config") public class ConfigController {     @Autowired     User user;     @Autowired     ContextRefresher contextRefresher;     @RequestMapping("/get")     public String get() {         return user.getName();     }     @RequestMapping("/refresh")     public String[] refresh() {         Set<String> keys = contextRefresher.refresh();         return keys.toArray(new String[keys.size()]);     }
  • application.yml

laker:   name: laker

操作流程如下:

1.瀏覽器http://localhost:8080/config/get - 瀏覽器結(jié)果:laker

2.修改application.yml里面內(nèi)容為:

laker:   name: lakerupdate

3.瀏覽器http://localhost:8080/config/refresh - 瀏覽器結(jié)果:laker.name

4.瀏覽器http://localhost:8080/config/get - 瀏覽器結(jié)果:lakerupdate(未重新啟動(dòng),實(shí)現(xiàn)了配置更新)

問題2.  Nacos客戶端如何實(shí)時(shí)監(jiān)聽到Nacos服務(wù)端配置更新了

這里可以去看下Nacos源碼,使用的是長輪詢,什么是長輪詢以及其其他替代協(xié)議?

  • RocketMQ

  • Nacos

  • Apollo

  • Kafka

自己花了幾個(gè)小時(shí)去看Nacos長輪詢?cè)创a,太多了不太好理解,有興趣的自行g(shù)oogle。一般我們都是基于Spring  Boot的后臺(tái)了,各種google后,發(fā)現(xiàn)Apollo實(shí)現(xiàn)較為簡單,所以直接拿Apollo的代碼借鑒。

1. Apollo 實(shí)現(xiàn)方式

實(shí)現(xiàn)方式如下:

  1. 鴻蒙官方戰(zhàn)略合作共建——HarmonyOS技術(shù)社區(qū)

  2. 客戶端會(huì)發(fā)起一個(gè)Http請(qǐng)求到Config  Service的notifications/v2接口,也就是NotificationControllerV2,參見RemoteConfigLongPollService

  3. NotificationControllerV2不會(huì)立即返回結(jié)果,而是通過Spring DeferredResult把請(qǐng)求掛起

  4. 如果在60秒內(nèi)沒有該客戶端關(guān)心的配置發(fā)布,那么會(huì)返回Http狀態(tài)碼304給客戶端

  5. 如果有該客戶端關(guān)心的配置發(fā)布,NotificationControllerV2會(huì)調(diào)用DeferredResult的setResult方法,傳入有配置變化的namespace信息,同時(shí)該請(qǐng)求會(huì)立即返回??蛻舳藦姆祷氐慕Y(jié)果中獲取到配置變化的namespace后,會(huì)立即請(qǐng)求Config  Service獲取該namespace的最新配置。

解讀下:

  • 關(guān)鍵詞DeferredResult,使用這個(gè)特性來實(shí)現(xiàn)長輪詢

  • 超時(shí)返回的時(shí)候,是返回的狀態(tài)碼Http Code 304

釋義:自從上次請(qǐng)求后,請(qǐng)求的網(wǎng)頁未修改過。服務(wù)器返回此響應(yīng)時(shí),不會(huì)返回網(wǎng)頁內(nèi)容,進(jìn)而節(jié)省帶寬和開銷。

2. 什么是DeferredResult

異步支持是在Servlet 3.0中引入的,簡單來說,它允許在請(qǐng)求接收器線程之外的另一個(gè)線程中處理HTTP請(qǐng)求。

從Spring 3.2開始可用的DeferredResult有助于將長時(shí)間運(yùn)行的計(jì)算從http-worker線程卸載到單獨(dú)的線程。

盡管另一個(gè)線程將占用一些資源來進(jìn)行計(jì)算,但不會(huì)阻止工作線程,并且可以處理傳入的客戶端請(qǐng)求。

異步請(qǐng)求處理模型非常有用,因?yàn)樗兄谠诟哓?fù)載期間很好地?cái)U(kuò)展應(yīng)用程序,尤其是對(duì)于IO密集型操作。

DeferredResult是對(duì)異步Servlet的封裝

具體可以參考我在CSDN寫的Spring Boot 使用DeferredResult實(shí)現(xiàn)長輪詢

這里借助互聯(lián)網(wǎng)上的一個(gè)圖就更清晰些。

Servlet異步流程圖

Config中怎么實(shí)現(xiàn)配置熱刷新

接收到request請(qǐng)求之后,由tomcat工作線程從HttpServletRequest中獲得一個(gè)異步上下文AsyncContext對(duì)象,然后由tomcat工作線程把AsyncContext對(duì)象傳遞給業(yè)務(wù)處理線程,同時(shí)tomcat工作線程歸還到工作線程池,這一步就是異步開始。在業(yè)務(wù)處理線程中完成業(yè)務(wù)邏輯的處理,生成response返回給客戶端。

3. 模擬造輪子

這里我們通過使用 Spring Boot 來簡單的模擬一下如何通過 Spring Boot DeferredResult 來實(shí)現(xiàn)長輪詢服務(wù)推送的。

代碼如下,僅供參考:

/**  * 模擬Config Service通知客戶端的長輪詢實(shí)現(xiàn)原理  */ @RestController @RequestMapping("/config") public class LakerConfigController {     private final Logger logger = LoggerFactory.getLogger(this.getClass());     //guava中的Multimap,多值map,對(duì)map的增強(qiáng),一個(gè)key可以保持多個(gè)value     private Multimap<String, DeferredResult<String>> watchRequests = Multimaps.synchronizedSetMultimap(HashMultimap.create());     /**      * 模擬長輪詢      */     @RequestMapping(value = "/get/{dataId}")     public DeferredResult<String> watch(@PathVariable("dataId") String dataId) {         logger.info("Request received");         ResponseEntity<String>                 NOT_MODIFIED_RESPONSE = new ResponseEntity<>(HttpStatus.NOT_MODIFIED);         // 超時(shí)時(shí)間30s 返回 304 狀態(tài)碼告訴客戶端當(dāng)前命名空間的配置文件并沒有更新         DeferredResult<String> deferredResult = new DeferredResult<>(30 * 1000L, NOT_MODIFIED_RESPONSE);         //當(dāng)deferredResult完成時(shí)(不論是超時(shí)還是異常還是正常完成),移除watchRequests中相應(yīng)的watch key         deferredResult.onCompletion(() -> {             logger.info("remove key:" + dataId);             watchRequests.remove(dataId, deferredResult);         });         deferredResult.onTimeout(() -> {             logger.info("onTimeout()");         });         watchRequests.put(dataId, deferredResult);         logger.info("Servlet thread released");         return deferredResult;     }     /**      * 模擬發(fā)布配置      */     @RequestMapping(value = "/update/{dataId}")     public Object publishConfig(@PathVariable("dataId") String dataId) {         if (watchRequests.containsKey(dataId)) {             Collection<DeferredResult<String>> deferredResults = watchRequests.get(dataId);             Long time = System.currentTimeMillis();             //通知所有watch這個(gè)namespace變更的長輪訓(xùn)配置變更結(jié)果             for (DeferredResult<String> deferredResult : deferredResults) {                 //deferredResult一旦執(zhí)行了setResult()方法,就說明DeferredResult正常完成了,會(huì)立即把結(jié)果返回給客戶端                 deferredResult.setResult(dataId + " changed:" + time);             }         }         return "success";     } }

操作流程如下:

為了簡便我用瀏覽器模擬,實(shí)際用Java Http Client,例如:okhttp、Apache http client等

正常流程:

  • client1瀏覽器http://localhost:8080/config/get/laker,阻塞中ing

  • client2瀏覽器http://localhost:8080/config/update/laker,返回success

  • client1瀏覽器http://localhost:8080/config/get/laker,返回laker  changed:1611022736865

超時(shí)流程:

  • client1瀏覽器http://localhost:8080/config/get/laker,阻塞中ing

  • 30s后

  • client1瀏覽器,返回http code 304

Config中怎么實(shí)現(xiàn)配置熱刷新

關(guān)于Config中怎么實(shí)現(xiàn)配置熱刷新問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI