How to set a timeout on a Hystrix command in Clojure?
我正在学习Hystrix和Clojure,但不了解如何(正确)在Clojure中的Hystrix命令上设置超时。
我搜索了StackOverflow和整个网络。我看了Hystrix的Clojure包装器源代码(https://github.com/Netflix/Hystrix/blob/master/hystrix-contrib/hystrix-clj/src/main/clojure/com/netflix/hystrix/core.clj)。有一个init-fn函数参数看起来很有希望,但是注释似乎表明这将不是一个可持续的解决方案。但这是一个简单的开始吗?
我在Clojure中运行了一个非常简单的Hystrix命令,希望能帮助您将其扩展为设置200ms的超时时间:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | (ns hystrix-timeout.core (:require [clojure.string :as str]) (:require [com.netflix.hystrix.core :as hystrix]) (:gen-class)) (defn my-primary [a] (if (= a true) (throw (Exception."Primary failed")) (str"primary:" a))) (defn my-fallback [a] (str"fallback:" a)) (hystrix/defcommand my-command {:hystrix/fallback-fn my-fallback} [a] (my-primary a)) (defn -main "Executes a simple Hystrix command. Will use a timeout when I know how to do this in Clojure." [& args] (println (my-command false)) (println (my-command true)) (System/exit 0) ; Exit explicitly as Hystrix threads are still running. ) |
我将我的lein项目放在https://github.com/oliverbaier/learning/tree/master/hystrix-timeout上,以防回答变得更容易。
非常感谢,
奥利弗
最简单的方法是仅使用系统属性。您可以设置全局默认值:
1 | (System/setProperty"hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds""200") |
或命令特定值:
1 | (System/setProperty"hystrix.command.my-command.execution.isolation.thread.timeoutInMilliseconds""200") |
您可以在-main方法中执行此操作。如果您运行的是真正的网络应用程序sans-main,则可以在project.clj中添加一个环初始化:ring {:handler your-handler:init your-config-method} your-config-method将在启动时被调用。