【问题标题】:Where should I save simple configuration settings?我应该在哪里保存简单的配置设置?
【发布时间】:2016-10-06 19:43:50
【问题描述】:

在我的 clojure Luminus/Compojure 应用程序中,我在 routes.clj 中有这个:

   (def page-size 12)
   (def images-path "/public/images/.....")

我需要将它们移动到某种配置中。最好的地方在哪里?我想要一些简单的东西,而不是在我已经使用的 Luminus 附带的库之上使用任何额外的库。

【问题讨论】:

    标签: clojure config compojure luminus


    【解决方案1】:

    Luminus 使用它的config 库进行配置。 You can put your configuration variables into appropriate config.edn files (per environment). 配置值可作为存储在config.core/env 中的映射使用。您可以在 <app>.core 命名空间中看到一个示例:

    (defn http-port [port]
      ;;default production port is set in
      ;;env/prod/resources/config.edn
      (parse-port (or port (env :port))))
    

    【讨论】:

    • 我可以在所有环境之间共享一个设置吗?例如,我希望page-size 在所有这些中始终等于 12,但我不想重复自己。
    • 我会编写自己的代码,该代码将读取具有通用配置的文件(例如common-config.edn)并将其与config.core/env 合并并改用它。
    • 我同样惊讶地发现 cprop 默认不读取任何常见的配置文件。使用 Luminus,将其添加到您的 config.clj: (defstate env :start (load-config :merge [(source/from-resource "common-config.edn")
    【解决方案2】:

    问自己这个问题:

    我是否希望在此设置不同的情况下多次部署我的应用程序?

    如果该问题的答案是“是”,那么配置应该由运行您的应用程序的环境通过edn 文件、Environ 或其他方式来规定。

    如果不是......那么你在谈论我将归类为应用程序常量的东西,这有助于避免magic numbers。在某些情况下,它可以通过将它们放置在特定的命名空间中来提高可读性。

    常量命名空间:

    (ns my.app.constants)
    
    (def page-size 12)
    (def images-path "/public/images/.....")
    

    应用:

    (ns my.app.core
      (:require [my.app.constants :as const)
    
    ;; now access the application constant like this
    ;; const/page-size
    
    (defn image-url [image-name]
      (str const/images-path "/" image-name))
    

    【讨论】:

      猜你喜欢
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      • 2015-01-22
      相关资源
      最近更新 更多