如何重构clojure/riemann代码

如何重构clojure/riemann代码,clojure,riemann,Clojure,Riemann,我正在与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 (aggregat

我正在与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)))))
为了稍微解释一下代码,我收到了如下事件:

  • :服务“cpu-0空闲”:公制58.23
  • :服务“cpu-1空闲”:公制98.11
  • :服务“cpu-2空闲”:公制12.23
我的目标是计算平均值,并在riemann中重新注入这一事件:

  • :服务“cpu平均值”:度量56.19
它起作用了,这不是问题所在。 但是正如您在第3到第10行中看到的,这里有很多重复的代码。我正在寻找一种重构代码的方法,但我被卡住了

我想用我的度量名称定义一个向量:

(def cpu-metrics ["user", "nice", "system", "idle", "interrupt", "softirq", "steal"])
…并使用它调用smap(聚合cpu度量

但我不知道怎么做。我试过map或doseq,但没有成功

你会怎么做

(更新/解决方案)

这是我的重构版本,在阅读了Arthur的答案之后

(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))))))

我可能会先提取名称并创建新的服务名称,然后使用服务名称和主机来拆分事件流,从而在某种程度上彻底改变函数

大概是这样的:

(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服务显示在统计信息中,而不更改您的监控代码。如果您不想这样做,您可以在其中添加另一个
,以明确接受您想要的服务。我这里没有测试这一点的设置,因此如果代码被破坏,请编辑:-)