gpt4 book ai didi

http - 使用带有 core.async channel 的 http-kit 长轮询

转载 作者:可可西里 更新时间:2023-11-01 16:37:55 29 4
gpt4 key购买 nike

我有一些长时间运行的进程,当进程完成时,它会返回一个带有结果的 core.async channel 。

现在我想通过 HTTP-kit 使用长轮询返回该结果。不幸的是,我有点困惑这样做的正确方法是什么。

目前我有一个处理程序(连接到路由)启动处理调用并在完成时发送结果:

(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))))))

它有效,但我不确定这是否是正确的方法。

编辑<!!正在阻塞 我现在正在 go-loop 中尝试非阻塞变体

(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))))))

最佳答案

为什么不在 go block 中的 channel 上发送?

(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 和分析器?

关于http - 使用带有 core.async channel 的 http-kit 长轮询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24549565/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com