【问题标题】:Duplication evaluation in clojure ringClojure环中的重复评估
【发布时间】:2017-03-23 02:54:49
【问题描述】:

我正在学习 Clojure 环。这是我的第一个处理程序:

(ns long-hdi.core
 (:gen-class))

(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (println "Hello, World!"){:body "hello" :status 200})

(defn on-init[](println "Initializing..."))
(defn on-destroy[](println "destroying..."))

这是project.clj配置文件:

   (defproject long-hdi "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"]]
  :plugins [[lein-ring "0.9.7"]]
  :ring {:handler long-hdi.core/-main :init long-hdi.core/on-init :destroy long-hdi.core/on-destroy}
  :main ^:skip-aot long-hdi.core
  :target-path "target/%s"
  :profiles {:uberjar {:aot :all}})

当我跑步时: lein ring 无头服务器 并浏览至http://localhost:3000 我看到它在控制台上打印“你好,世界!”两次。为什么打印2次?我想它只打印一次。 然后我修改源代码为:

...{:body args :status 200}...

然后使用谷歌浏览器浏览到http://localhost:3000 这一次,它打印出“你好,世界!”在控制台上 3 次。为什么改为打印3次?

我正在使用 REPL-y 0.3.7、nREPL 0.2.12、Clojure 1.8.0、lein-ring "0.9.7"、Windows 10-64 位。

【问题讨论】:

  • 我想发生的事情是您在更改代码后调用-main,并在您的控制台上累积Hello, World!s。
  • 不,绝对不。我没有计算累积的结果。每次浏览器刷新都会产生 2 个“Hello, world!”。
  • -main 是您的处理程序吗?您应该使用其他函数作为处理程序。 -main 只能用作应用程序的入口点。
  • 是的,它是处理程序。我刚刚将-main 重命名为other-functions。结果相同。
  • 您能否编辑您的问题,并粘贴您文件中的所有代码。

标签: clojure ring


【解决方案1】:

问题不是因为你的代码而发生的,但我将在下面向你展示如何修改你的代码以获得你想要的结果。

要在此处进行更多调查,请打开 Chrome 开发工具窗口(右键单击并选择“检查”)。转到顶部的网络选项卡。在左侧,您会在请求列表下看到一些有趣的内容:localhost 以及 favicon.ico。因此,实际上,每次重新加载浏览器时,它不仅对页面发出请求,而且对页面图标也发出请求,这就是您看到两个请求的原因。 Firefox(至少在我的情况下)只是在第一次加载后缓存图标,但 chrome 每次都从服务器请求它。

那么,你能做些什么呢?好吧,浏览器的每个 请求都会调用same 处理程序。因此,您需要接下来探索路线。这允许您将 特定 浏览器请求映射到 特定 处理程序。因此,您可以简单地避免调用获取favicon。作为一个帮助您入门的小示例,它可以让您在浏览器窗口中查看请求,而不是打印到命令行:

你的项目.clj:

(defproject long-hdi "0.1.0-SNAPSHOT"
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [ring/ring-core "1.5.1"]
                 [ring/ring-jetty-adapter "1.5.1"]
                 [compojure "1.5.2"]]
  :main long-hdi.core)

在你的主源文件中:

(ns long-hdi.core
  (:require [ring.adapter.jetty]
            [compojure.core :refer :all]))

(def counter (atom 0))

(defn handler
  [req]
  (swap! counter inc)
  {:body (str "counter is: " @counter) :status 200})

(defroutes app
  (GET "/" [] handler))

(defn -main [& args]
  (ring.adapter.jetty/run-jetty app {:port 3000}))

运行服务器,然后在 localhost:3000 的浏览器窗口中打开它:

$ lein run

我希望这会有所帮助,并且玩得开心!

【讨论】:

  • 谢谢!我没有想到图标。
猜你喜欢
  • 2012-11-19
  • 1970-01-01
  • 1970-01-01
  • 2011-03-03
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-01
相关资源
最近更新 更多