`(chan n)` 和 `(chan (buffer n))` 有什么区别?

Any difference between `(chan n)` and `(chan (buffer n))`?

如题所问,(chan n)(chan (buffer n))在使用上有什么区别吗?

这个问题源于我想从数据库中提取消息(是的,我不想使用 Kafka 或 RabbitMQ)并按顺序处理它们的想法。

因此代码段如下所示:

(defn processer [id]
  (let [ch (chan (buffer 1000))]  ;;(chan 1000) or (chan (buffer 1000))?
    (go-loop []
      (when-let [msg (<! ch)]
        (process-msg msg))
      (recur))
    ch))

(defn enqueue [id]
  (let [ch (processer id)]
    (go-loop []
      (let [msgs (take-100-msg-from-db id)]
        (if (seq msgs)
          (doseq [msg msgs]
            (>! ch msg))
          (<! (timeout 100))))
      (recur))))

在我的测试中,他们的行为没有区别。

是的,它们是一样的。

你可以随时查看 source:

(defn chan
  ([] (chan nil))
  ([buf-or-n] (chan buf-or-n nil))
  ([buf-or-n xform] (chan buf-or-n xform nil))
  ([buf-or-n xform ex-handler]
     (channels/chan (if (number? buf-or-n) (buffer buf-or-n) buf-or-n) xform ex-handler)))