我有一些长时间运行的进程,当进程完成时,返回一个带有结果的core.async通道。
现在,我想使用HTTP使用长轮询来返回结果。不幸的是,我有点搞不懂这样做的正确方式是什么。
目前,我有一个处理程序(连接到一个路由),它启动处理调用并在完成时发送结果:
(defn handler
[request]
(let [c (process request)] ;; long running process that returns a channel
(http/with-channel request channel
(http/send! channel {:status 200
:body (<!! (go (<! c)))))
(http/on-close channel (fn [_] (async/close! c))))))有效,但我不确定这是不是正确的方法。
编辑,因为<!!是阻塞的,我现在正在尝试一个非阻塞变体的围棋循环。
(defn handler
[request]
(let [c (process request)]
(http/with-channel request channel
(async/go-loop [v (<! c)]
(http/send! channel {:status 200
:body v}))
(http/on-close channel (fn [_] (async/close! c))))))发布于 2014-07-03 09:26:38
为什么不在围棋区发送频道呢?
(http/with-channel request channel
(go (http/send! channel (<! c))))<!!阻塞了-因此,仅仅在处理程序中直接调用<!! c并没有真正的优势:
(defn handler [request] (let [c (process request)] ;; long running process that returns a channel {:status 200 :body (<!! c)}))
针对问题更新进行编辑:更新后的代码可以工作--这是一个功能齐全的命名空间,适合我:
(ns async-resp.core
(:require [org.httpkit.server :as http]
[clojure.core.async :as async :refer (<! >! go chan go-loop close! timeout)]))
(defn process
[_]
(let [ch (chan)]
(go
(<! (timeout 5000))
(>! ch "TEST"))
ch))
(defn test-handler
[request]
(let [c (process request)]
(http/with-channel request channel
(go-loop [v (<! c)]
(http/send! channel {:status 200
:body v}))
(http/on-close channel (fn [_] (close! c))))))
(defn run
[]
(http/run-server test-handler {}))然而,到目前为止,我不得不手动将tools.analyzer.jvm依赖项添加到project.clj中--因为我按原样使用core.async获得编译失败。
检查你在运行最新的core.async和分析器吗?
https://stackoverflow.com/questions/24549565
复制相似问题