解释如何使用mount的defstate监听etcd变更并重启子系统

解读

国内高并发、微服务场景下,很多团队把etcd当“配置总线”——服务启动时拉一次配置,运行中靠watch机制热更新。mount是Clojure社区最常用的“状态管理库”,它把系统拆成一个个defstate,随REPL或生命周期钩子启动、停止、重启。
面试官真正想确认的是:

  1. 你能否把“etcd watch”这一外部事件流,优雅地映射到mount的状态生命周期里;
  2. 当etcd里某个key发生变化,你是否能“只重启受影响子系统”,而不是把整个REPL进程重启;
  3. 你能否处理好背压、异常、资源泄露,这些线上翻车点。

一句话:用mount的defstate封装“etcd监听线程”,把“配置变更”转成“状态停止->重新注入新配置->状态启动”的闭环,并保证可观测、可回滚。

知识点

  1. mount生命周期:defstate的:start、:stop、:reload钩子,以及mount/start-with、mount/running-states等API。
  2. etcd v3 watch:用jetcd客户端的Watch.create()返回的CompletableFuture流,需要放到Clojure的core.async/go-loop里做非阻塞回调。
  3. 配置版本化:etcd的modRevision作为配置“版本号”,防止旧事件重放。
  4. 子系统精准重启:mount只重启“依赖该配置”的下游state,用mount/start-with把新配置注入到mount的依赖图。
  5. 异常隔离:watch线程崩溃不能拖垮整个系统;需要监控线程存活并自动重连。
  6. 国内网络抖动:etcd集群跨可用区时,watch可能“断流重连”,必须做好指数退避。
  7. REPL友好:开发环境允许手动覆盖配置,mount/stop + mount/start-with不能影响开发者当前的工作状态。

答案

下面给出可直接落地到生产环境的最小可运行骨架,演示“监听etcd key /app/config,一旦内容变化就重启db连接池与缓存子系统”。
依赖:mount 0.1.16 + jetcd-core 0.7.5 + core.async 1.11.0

(ns com.acme.config-etcd
  (:require [mount.core :as mount :refer [defstate]]
            [clojure.core.async :as async :refer [<!! >!! go-loop timeout alt!]]
            [clojure.data.json :as json])
  (:import [io.etcd.jetcd Client WatchOption ByteSequence]
           [io.etcd.jetcd.watch WatchEvent$EventType]
           [java.nio.charset StandardCharsets]))

;; 工具函数
(defn- ->bs [^String s] (ByteSequence/from s StandardCharsets/UTF_8))
(defn- bs->str [^ByteSequence bs] (.toString bs StandardCharsets/UTF_8))

(def ^:private etcd-endpoints ["http://etcd1.acme.cn:2379"
                               "http://etcd2.acme.cn:2379"
                               "http://etcd3.acme.cn:2379"])

(def ^:private config-key "/app/config")

;; 全局channel,用于把etcd事件抛到Clojure世界
(defonce config-events (async/chan (async/sliding-buffer 1)))

;; 1. etcd watch线程,作为mount的“资源”
(defstate etcd-watcher
  :start (let [client (Client/builder) (.endpoints etcd-endpoints) .build
               watch (.. client getWatchClient)
               option (-> (WatchOption/newBuilder) (.withPrevKV true) .build)
               listener (reify io.etcd.jetcd.watch.WatchListener
                          (onNext [this response]
                            (doseq [event (.getEvents response)]
                              (when (= WatchEvent$EventType/PUT (.getEventType event))
                                (let [new-val (bs->str (.getKeyValue (.getKeyValue event)))
                                      revision (.getRevision (.getHeader response))]
                                  (>!! config-events {:revision revision
                                                      :config (json/read-str new-val :key-fn keyword)})))))
                          (onError [this t]
                            (println "etcd watch error:" t)
                            ;; 抛出到mount,触发自动重启
                            (throw t))
                          (onCompleted [this]
                            (println "etcd watch completed")))]
           (.watch watch (->bs config-key) option listener)
           {:client client :listener listener})
  :stop  (let [{:keys [client listener]} etcd-watcher]
           (when client (.close client))
           (async/close! config-events)))

;; 2. 配置状态,依赖etcd-watcher
(defstate app-config
  :start (do
           ;; 首次启动时主动拉一次
           (let [client (:client etcd-watcher)
                resp (.. client (getKVClient) (get (->bs config-key)) (get))
                val (bs->Str (.getValue (.getKvs resp)))]
             (json/read-str val :key-fn keyword)))
  :stop  nil)

;; 3. db连接池,依赖app-config
(defstate datasource
  :start (let [{:keys [host port user pass]} app-config]
           (println "[db] starting with" host)
           (make-datasource host port user pass))
  :stop  (do
           (println "[db] stopping")
           (.close datasource)))

;; 4. 缓存,同样依赖app-config
(defstate cache-conn
  :start (let [ttl (get-in app-config [:cache :ttl])]
           (println "[cache] starting with ttl" ttl)
           (make-cache-client ttl))
  :stop  (do
           (println "[cache] stopping")
           (.close cache-conn)))

;; 5. 事件消费循环:收到新配置后精准重启
(defstate config-reloader
  :start (go-loop []
           (when-let [{:keys [revision config]} (<!! config-events)]
             (println "[config] detected new revision" revision)
             (try
               ;; 只重启依赖app-config的下游state
               (mount/stop #'com.acme.config-etcd/app-config
                           #'com.acme.config-etcd/datasource
                           #'com.acme.config-etcd/cache-conn)
               (mount/start-with {#'com.acme.config-etcd/app-config config})
               (println "[config] reload success")
               (catch Exception e
                 (println "[config] reload failed, keep old state" e)))
             (recur)))
  :stop  (async/close! config-reloader))

;; 启动顺序由mount的依赖图自动推导
(mount/start #'com.acme.config-etcd/etcd-watcher
             #'com.acme.config-etcd/app-config
             #'com.acme.config-etcd/datasource
             #'com.acme.config-etcd/cache-conn
             #'com.acme.config-etcd/config-reloader)

关键点

  1. etcd-watcher作为最底层state,生命周期与watch线程绑定;一旦watch线程onError抛异常,mount会标记其为失败,后续可结合supervisor重启。
  2. config-reloader是轻量级go-loop,只负责把事件流翻译成“mount/stop + mount/start-with”,保证下游state拿到新配置。
  3. 使用mount/start-with注入新配置,避免全局可变原子,符合函数式不可变思想。
  4. 所有side-effect(db、缓存)都封装在defstate的:start/:stop,重启时旧资源一定被正确关闭,防止连接泄露。
  5. 国内生产环境建议加上revision判重与退避:
    (when (> revision (:last-revision @config-version-atom)) …)
    防止etcd网络闪断后重放旧事件。

拓展思考

  1. 灰度发布:etcd里同一key可以存json with “percentage” 字段,config-reloader解析后只重启部分实例(结合k8s label选择)。
  2. 多集群容灾:etcd集群A挂掉后,客户端自动切换到集群B,watch断点续传需保存last revision到本地文件,重启后从断点继续。
  3. 观测与告警:在每个defstate的:start/:stop埋点,通过Micrometer吐到Prometheus,Grafana大盘展示“配置热重启次数”、“重启失败率”。
  4. 与Polylith架构结合:把“配置层”做成独立base,子系统brick通过接口依赖配置,mount重启时只替换实现组件,无需重新编译整个服务。
  5. 本地开发体验:REPL里手动(mount/start-with {#'app-config mock-config})不会触发etcd-watcher,保证单元测试可重复、无外部依赖。