2
我發現/學習Clojure的黎曼和我寫了下面的代碼聚集每個主機我的CPU指標:如何重構這個的Clojure /黎曼代碼
(streams
(by [:host]
smap (aggregate-cpu-metrics "user" folds/mean)
smap (aggregate-cpu-metrics "nice" folds/mean)
smap (aggregate-cpu-metrics "system" folds/mean)
smap (aggregate-cpu-metrics "idle" folds/mean)
smap (aggregate-cpu-metrics "wait" folds/mean)
smap (aggregate-cpu-metrics "interrupt" folds/mean)
smap (aggregate-cpu-metrics "softirq" folds/mean)
smap (aggregate-cpu-metrics "steal" folds/mean)))
(defn aggregate-cpu-metrics
[name, aggr]
(where (service (re-pattern (str "cpu-[0-9]+ " name)))
(coalesce 10
(smap aggr
(with :service (str "cpu-average " name) reinject)))))
要解釋代碼一點點,我收到事件這樣的:
- :服務 「CPU-0空閒」:公制58.23
- :服務 「CPU-1空閒」:公制98.11
- :服務 「CPU-2空閒」 :公制12.23
而且我的目標是計算平均值和黎曼重新注入這個事件:
- :服務「的CPU平均」:公制56.19
它的工作,這不是問題。 但正如你可以在第3到第10行看到的,這裏有很多重複的代碼。我正在尋找一種重構此代碼的方式,但我被卡住了。
我想確定我的名字指標向量:
(def cpu-metrics ["user", "nice", "system", "idle", "interrupt", "softirq", "steal"])
...並用它來調用SMAP(合計CPU的度量 ...
但我不知道該怎麼做。我已經試過地圖或doseq,但沒有成功。
你會怎麼做呢?
(更新/解決方案):
這裏是我的重構後的版本,閱讀亞瑟的答案後。
(streams
(where
(service #"^cpu-[0-9]+ ")
(adjust
[:service #(clojure.string/replace % #"^cpu-[0-9]+" "cpu-average")]
(by [:host :service]
(fixed-time-window 10 (smap folds/mean reinject))))))