0

我迷失了所有这些异步/多线程库和本机 clojure 功能。

我有一个 web 服务,它调用一个外部 API,转换它的响应,然后返回给客户端。现在是用 Python 编写的。我想让每个客户端在一个单独的线程中执行它的请求,这样他们就不会等待对方完成,或者服务器异步。不涉及繁重的计算,只等待IO。

我认为使用 clojure 会很容易,但我错过了一些东西...... Aleph 是异步服务器,对吗?但是,当我模拟wait内部请求处理程序时,整个服务器都在等待,而不仅仅是客户端。所以我不太明白这里异步的意义?

据我了解,这可能是错误的,异步服务器永远不会阻塞 IO 操作?可能sleep是模拟等待 IO 的坏方法?

编辑我创建了一个愚蠢的等待服务,我从 Clojure 的 Aleph 服务器调用它,但请求处理仍然是顺序的

(ns aleph-t.core
 ( :require [aleph.http :as http]
            [aleph.netty :as netty]))

(defn heavy [] (Thread/sleep 10000) "hello!")

(defn handler [req]
  {:status 200
   :headers {"content-type" "text/plain"}
   :body (heavy)})
; need to wait otherwise server is closed
(defn -main [& args]
  (netty/wait-for-close (http/start-server handler {:port 8080}))
  )
4

1 回答 1

3

When writing an asynchronous backend you need to keep in mind that you must not use blocking method calls because those will block your asynchronous worker threads and thus your whole backend.

The basic idea of asynchronous programming is to have your worker threads do real CPU work mainly and use callbacks (or channels or streams or manifolds, etc..) for every other potentially blocking operation. This way asynchronous programming can give your application higher throughput.

In your example the (Thread/sleep .) blocks a worker thread.

When using aleph for HTTP you can use the manifold library for asynchronous IO.

There are a few examples of using aleph with manifold. For example, you could use core.async timeouts for simulating a long-running task as seen in this example.

于 2017-10-02T07:08:31.747 回答