You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用httr2的req_perform_parallel时API请求缓存失败问题

解决httr2并行请求缓存不生效的问题

问题排查

你的代码能正常获取API数据但缓存目录为空,核心原因有两个:

  • 多级缓存目录未提前创建,httr2不会自动递归生成目录结构
  • 为每个请求单独设置缓存目录的方式没必要,反而可能导致缓存逻辑识别异常(httr2会自动根据请求特征生成唯一缓存文件,无需单独目录)

修复方案

1. 提前创建缓存目录

先确保缓存根目录存在,避免因目录缺失导致缓存写入失败:

# 递归创建缓存目录,不存在则创建,已存在则忽略警告
dir.create(file.path("cache", "citePull"), recursive = TRUE, showWarnings = FALSE)

2. 简化缓存配置(推荐)

无需为每个请求单独设置缓存目录,统一使用根目录即可,httr2会自动根据请求的URL、参数等生成唯一哈希文件名,确保缓存不冲突:

library(httr2)

# 构造请求列表
citeLst <- list(
  one = paste(17038628,17320734,16677657, sep=","),
  two = paste(17380955,17299329,17297311, sep=","),
  three = paste(17280498,17141525,17262759, sep=",")
)
citeLst <- lapply(citeLst, function(x) paste0("https://icite.od.nih.gov/api/pubs?pmids=", x))
reqLst <- lapply(citeLst, request)

# 为所有请求配置统一缓存目录
cacheLst <- lapply(reqLst, function(req) {
  req_cache(
    req,
    path = file.path("cache", "citePull"),
    use_on_error = TRUE  # 可选:请求失败时使用缓存(如果存在)
  )
})

# 并行执行请求
respLst <- req_perform_parallel(cacheLst)

3. 保留单独目录的修复(若有特殊需求)

如果必须为每个请求单独设置缓存目录,需确保每个子目录都被提前创建:

cacheLst <- mapply(function(req, dir_name) {
  # 创建当前请求的专属缓存目录
  sub_cache_path <- file.path("cache", "citePull", dir_name)
  dir.create(sub_cache_path, recursive = TRUE, showWarnings = FALSE)
  
  # 配置缓存
  req_cache(req, path = sub_cache_path)
}, reqLst, names(citeLst), SIMPLIFY = FALSE)

respLst <- req_perform_parallel(cacheLst)

验证缓存是否生效

执行完请求后,检查缓存目录是否生成文件:

# 检查统一缓存目录下的文件
list.files(file.path("cache", "citePull"))

# 若用单独目录,检查其中一个子目录
list.files(file.path("cache", "citePull", "one"))

内容的提问来源于stack exchange,提问作者bcarothers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 10:32:46