[英]How to implement async calls in R HTTPUV startServer?
R httpuv startServer
function 應該在 app 參數的調用部分支持異步處理,但我無法讓它工作。 有誰知道如何做到這一點? 下面的示例不起作用,但它顯示了我正在嘗試執行的操作,異步運行每個請求(或特定頁面),以便在另一個請求正在處理時加載頁面。
startServer(
host,
port,
app = list(
call = function(req) {
req <- list(
"REQUEST_METHOD" = req$REQUEST_METHOD,
"SCRIPT_NAME" = req$SCRIPT_NAME,
"PATH_INFO" = req$PATH_INFO,
"QUERY_STRING" = req$QUERY_STRING,
"SERVER_NAME" = req$SERVER_NAME,
"SERVER_PORT" = req$SERVER_PORT,
"HEADERS" = req$HEADERS,
"rook.input" = req[["rook.input"]]$read_lines()
)
future_promise({
if(req$PATH_INFO %in% valid_dynamic_paths){
x <- eval(dynamic[[req$PATH_INFO]][req$REQUEST_METHOD])
list(
status = x[["status"]],
headers = x[["headers"]],
body = x[["body"]]
)
}else{
list(
status = 404,
headers = list(
'Content-Type' = 'text/html'
),
body = "404. Page not found."
)
}
})
},
staticPaths = static
)
)
我能夠得到類似於工作的東西。 下面的代碼顯示了它的要點:
# fork a process for each new request
future::plan(future::multicore)
httpuv::runServer("0.0.0.0", 8080, list(
call = function(req) {
# `as.promise` is necessary, because `httpuv` is using `is.promise`
# under the hood to act differently. Unfortunately `is.promise` returns
# `FALSE` for a `future`.
promises::as.promise(
future::future({
Sys.sleep(5)
# Respond with HTTP 200 OK
list(
status = 200,
body = "Slept for 5 seconds",
headers = list(
# Content-Type is important, otherwise you will run
# into a "not compatible with STRSXP" error.
"content-type" = "text/plain"
)
)
})
)
}
))
在(幾乎)同時調用服務器請求,將表明您只等待兩個請求的 5 秒,而不是一個等待 5 秒,另一個等待 10 秒。
time curl -s localhost:8080 > /dev/null &
time curl -s localhost:8080 > /dev/null
# After 5 seconds you should see output similar to the following:
# real 0m5.089s
# user 0m0.011s
# sys 0m0.010s
# real 0m5.112s
# user 0m0.020s
# sys 0m0.024s
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.