2015-01-14 42 views
1

我有一個clojure環網工程,我希望能夠根據配置文件設置端口號。目前,我有從project.clj下面的代碼片段如何根據配置文件設置環網端口

:plugins [[lein-ring "0.8.13"]] 
:ring {:handler project.handler/webServer 
     :init project.init/initialize 
     :port 80} 
:profiles {:dev  {:jvm-opts ["-Dproperty-file=dev.properties"]} 
      :ci   {:jvm-opts ["-Dproperty-file=ci.properties"]} 
      :uberjar {:aot :all}}) 

我想要做的是將端口設置爲8080開發環境,然後對生產環境的端口80。我會始終在端口80上運行,但這需要root權限,而不是我想要爲dev運行執行的操作。我嘗試過(盲目地)將環端口放入uberjar配置文件中,但這不起作用。我也嘗試使用environ project來設置基於環境變量的環路端口,但這也不起作用。

我打開一個解決方案,將命令行參數傳遞給java -jar [...]-standalone.jar命令,但我堅持如何獲得任何工作方法。

回答

2

你不需要environ。當您需要訪問源代碼中的配置變量時使用它。在project.clj你可以直接做到這一點:

:profiles {:dev  {:jvm-opts ["-Dproperty-file=dev.properties"] 
         :ring {:port 8080}} 
      :ci   {:jvm-opts ["-Dproperty-file=ci.properties"] 
         :ring {:port 80}} 
      :uberjar {:aot :all 
         :ring {:port 80}}}) 

我已經測試了這個(不jvm-opts和8081端口,而不是80)和它的作品。

替代方案:如果他們是不同的機器,您可以使用操作系統的環境變量:

:ring {:handler project.handler/webServer 
     :init project.init/initialize 
     :port ~(System/getenv "RING_PORT")} 

,然後在開發計算機和80設置RING_PORT到8080上機生產。

$ export RING_PORT=80 
+0

這對我有效。我意識到,即使在運行「ring uberjar」目標時,我仍然在使用「dev」配置文件。這是令人困惑的部分。我不得不改變添加'with-profile ci'來獲取正確的端口。 –

0

看起來替代版本不能如上所述工作。我得到異常「java.lang.String不能轉換爲java.lang.Number」。顯然我們必須將值環境變量明確地解析爲整數,但是我們也必須捕獲可能的錯誤。代碼適用於我

:port ~(try 
       (Integer/valueOf 
       (System/getenv "RING_PORT")) 
       (catch Exception e 3000))