我正在使用Riemann发现/学习Clojure,并编写了以下代码来聚合每个主机的CPU指标:
(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)))))为了稍微解释一下代码,我收到了这样的事件:
我的目标是计算平均值,然后在黎曼再弹出这个事件:
起作用了,这不是问题所在。但是,正如您在第3至第10行中所看到的,这里有很多重复的代码。我正在寻找一种方法来重构这段代码,但我被困住了。
我想用我的度量名称定义一个向量:
(def cpu-metrics ["user", "nice", "system", "idle", "interrupt", "softirq", "steal"])...and使用它来调用smap(聚合-cpu-度量.
但我不知道该怎么做。我试过地图或多塞克,但都没有成功。
你会怎么做?
(更新/解决方案):
这是我在阅读了亚瑟的答案后,重新演绎的版本。
(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))))))发布于 2015-02-06 22:19:00
通过首先提取名称并创建新的服务名称,然后使用服务名称和主机来拆分事件流,我可能会将该函数翻转。
就像这样:
(streams
(where (service #"cpu-[0-9]+ ")
(adjust [:service (fn [service]
(str "cpu-average "
(second (clojure.string/split service #"cpu-[0-9]+ "))))]
(by [:host :service] ... )))这有一个副作用,允许在不更改监视代码的情况下在统计数据中显示任何cpu服务。如果您不想这样做,可以添加另一个where来显式地接受您想要的那些。我这里没有测试这个的设置,所以如果代码坏了,请编辑:-)
https://stackoverflow.com/questions/28374871
复制相似问题