A Chain of Spring-OSGi Services

0

源起

使用 TargetSourceLifecycleListener 可以讓客端在服務發生變動時加以因應,這是一對一的場景, 如果是一連串的相依服務串在一起的場景,要如何因應某個 bundle 的變化。

參考

  1. Hello TargetSourceLifeCycleListener

場景

下面為練習場景,假設 http 啟動的 port 由 conf bundle 控制。

  1. Conf Bundle(ConfService)
  2. Jetty Bundle(ConfListener/JettyService)
  3. WebApp Bundle(JettyListener)

修改 Conf Bundle 後先停止。

Stop ConfBundle

  1. [Jetty Bundle] ConfListener.unbind
  2. [Conf Bundle] ConfService.destroy

然後啟動,這時候會在 bind 中如果發現 port 不同會重新啟動

Start ConfBundle

  1. [Conf Bundle] ConfService.init
  2. [Jetty Bundle] ConfListener.bind (restart http service)

這時候 WebAppBundle 一無所知,因為 JettyBundle 沒有被 stop/start, 而是 ConfBundle stop/start。

這時要這些 WebAppBundle 重新註冊,需要 JettyBundle 的 stop/start, 來觸動 JettyListener。

Stop JettyBundle

  1. [WebApp Bundle] JettyListener.unbind
  2. [Jetty Bundle] JettyService.destroy (stop http service)
  3. [Jetty Bundle] ConfListener.unbind

Start JettyBundle

  1. [Jetty Bundle] JettyService.init (start http service)
  2. [Jetty Bundle] ConfListener.bind (restart service)
  3. [WebApp Bundle] JettyListener.bind

這時候因為整個 JettyBundle 的重新啟用,導致屬於這個 bundle 的 ApplicationContext 再來一次,這讓 ConfListener.bind 又被呼叫一次。

bind 被呼叫兩次的原因。

  1. service 端重新啟動觸發 bind method。
  2. bundle 本端重新啟動,為了觸發下游 bundle 的 bind method。

setter method to inject ConfService

為了避免呼叫兩次,一開始將 bind 的 restart http service 去掉,只讓 init 啟動,不過發現 bind 的方式必須在 bean 實體化之後,也就是說在 init 之後才會呼叫 bind,如此一來要設定讓 http service 使用修改後的 port 會有 問題。

另外可以在 init 之前完成的是 setter 注入 ConfService 的方式,這樣一來, ConfBundle 的重新啟動,並不會對 JettyService 有任何作用,改 port 的行為 必須直到 JettyBundle 重新啟動才會生效。

觀察

  1. ConfBundle 一改,下面的相關 Bundle 也需要跟著重新啟動,來觸發下游的 bind method, 以修改 port 為例,需要 ConfBundle,JettyBundl 兩個 bundle 先後依順序重新啟動。
  2. ConfBundle 修改導致所有相關 Bundle 都需各別再啟動的方式也許有其他更好做法,有待繼續觀察。
  3. bind/unbind 需要由可由輸出服務的 bundle start/stop 觸發,也會由自己的 bundle start/stop 觸發。
  4. stop bundle 會先呼叫 bean unbind method 後呼叫 bean destroy method。
  5. start bundle 會先呼叫 bena init method 後呼叫 bean bind method。

Comments

(leave url/email »)

   Preview comment