【问题标题】:Clojure compile timeClojure 编译时间
【发布时间】:2017-12-11 14:29:14
【问题描述】:

我是第一次测试 Clojure,想写一个简单的 websocket 客户端应用程序。我找到了库https://github.com/stylefruits/gniazdo 并让代码工作(使用lein run)。但是,将代码编译到 jar 中(lein jarlein uberjar 要么被卡住,要么需要很长时间(大约 1 小时后中止))

步骤:

  1. lein new app testing
  2. 修改了 src/testing/core.clj 和 project.clj(见下文)
  3. lein jar(或lein uberjar

为简单起见,我有这个非常简单的代码,它已经需要很长时间才能编译成一个 jar:

(ns testing.core
  (:gen-class))

(require '[gniazdo.core :as ws])

(def socket
    (ws/connect
            "wss://some.url.com/"))

(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (ws/close socket))

project.clj:

(defproject testing "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [stylefruits/gniazdo "1.0.1"]]
  :main ^:skip-aot testing.core
  :aot [testing.core]
  :target-path "target/%s"
  :profiles {:uberjar {:aot :all}})

运行lein jar的输出:

$lein jar
Compiling testing.core
2017-12-11 14:15:14.813:INFO::main: Logging initialized @1352ms

什么都没有。这是正常行为(编译只需要很长时间)还是我在这里遗漏了什么? Clojure 看起来很有趣,但如果编译这么小的程序需要几个小时,那么在我的情况下部署可能是个问题。

【问题讨论】:

  • 要么:1. 不要在顶层连接,要么:2. 不要 AOT 你的 testing.core 命名空间。您认为应该如何将连接存储在 JAR 中?

标签: clojure compilation leiningen


【解决方案1】:

当该命名空间被编译时提前(您的 project.clj 中的:aot [testing.core]),此代码在编译期间被评估:

(def socket
  (ws/connect "wss://some.url.com/"))

这可能是导致挂起的原因。编译器永远不会继续这样做,因为它已经进行了阻塞调用。

  1. 如果您不需要 :aot 指令,您可以删除它(而且您可能不需要)。我认为在创建新的 Leiningen 项目时,这可能是一个有点令人困惑的默认设置。

  2. 你可以做一些事情,比如将套接字/conn 包装在 delay 中:

    (def socket (delay (ws/connect "wss://some.url.com/")))
    

    然后deref/@ 在您需要价值的任何地方。这只是延迟ws/connect 的评估,直到您提出要求。

【讨论】:

  • 我不确定我是否理解正确:AOT 编译实际上是执行代码,而不是创建代表套接字定义的字节码?在那种情况下,这也可以工作:(defn socket [url] (ws/connect url))
  • @Moe 是的,编译 clojure 代码的唯一方法是执行它所在的命名空间。
猜你喜欢
  • 2011-12-26
  • 2011-03-08
  • 2013-01-03
  • 1970-01-01
  • 2013-10-13
  • 2011-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多