如何绑定动态变量?

How do I bind a dynamic variable?

如何在 compojure 中绑定动态变量?请看下面我的例子,这里的 request-id 是一个唯一的 uuid,它是为每个 api 请求生成的。我希望能够在后续的日志记录等方法中访问此请求 ID。我尝试使用绑定功能,但仍然无法在 [=] 中访问 request-id 12=]。

handler.clj

(ns some_app.handler
  (:require
    [compojure.api.sweet :refer :all]
    [compojure.route :as route]
    [some_api.some_page :as some-page]))

(def ^:dynamic *request-id*
  nil)

(defn ^:private generate-request-id []
  (str (java.util.UUID/randomUUID)))

(def app
  (binding [*request-id* (generate-request-id)]
    (api
      (context "/api" [] (GET "/some-page" [] (some-page/some-method))))))

一些-page.clj

(ns some_app.some_page
(:require
        [clojure.tools.logging :as log]))

(def some-method []
  (log/info {:request-id *request-id*}))

这里对绑定的调用是在错误的地方。绑定应该在处理请求时生效,而不是在构造 app/api 时生效。

你想要一些中间件来做这个:

(defn with-request-id 
  [f]
  (fn [request]
    (binding [*request-id* (generate-request-id)]
      (f request)))

(def app
  (with-request-id
    (api ... ))

另见 Ring Concepts

在您的 some_app.some_page 命名空间中,您需要 require 声明 *request-id* 的命名空间。类似于:

(ns some_app.some_page
  (:require
    [clojure.tools.logging :as log]
    [some_app.handler :as hndlr))

然后你可以参考*request-id*喜欢:

(def some-method []
  (log/info {:request-id hndlr/*request-id*}))

动态绑定是一种很好的方法,并且随着代码库的增长,它会随着时间的推移而变得笨拙,至少与在请求中存储有关请求的数据相比是这样。

环形模型鼓励将有关请求的内容直接作为数据存储在请求中,而不是在元数据或环境中,例如绑定变量。

(defn with-request-id 
  [f]
  (fn [request]
      (f (assoc request :request-id (generate-request-id)))

那么您就不必担心线程绑定的保存位置或其他此类问题。