我从外部 API 请求数据,并将其直接写入 Cloud Storage 文件。数据写入很好,但是当我扩展时,我遇到了内存问题并达到了 GAE 实例的 1024 MB 限制。
这些是我遇到的严重错误:
Exceeded soft private memory limit of 1024 MB with 1425 MB after servicing 46 requests total
这是我正在使用的代码的摘要:
import cloudstorage as gcs
import urllib2
# Example file path
filePath = '/bucket/dir/file.gzip'
def deferrableTask(filePath, api_url, post_body):
with gcs.open(filePath, 'w') as f:
request = urllib2.Request(api_url, post_body)
try:
response = urllib2.urlopen(request, timeout = 600)
except urllib2.HTTPError, e:
raise customError(e)
else:
while True:
chunk = response.read(16 * 1024)
if not chunk: break
f.write(chunk)
f.close()
del f
gc.collect()
上面的任务可以使用任务队列来延迟。队列中最多可以同时运行 40 个。在我的 app.yaml
中,我有以下设置:
instance_class: F4_1G
automatic_scaling:
max_concurrent_requests: 4
此代码适用于将 api 数据写入云存储。当我开始执行数百个这样的请求时,我开始遇到内存问题。
请求的 gzip 文件大小在 300 kb 到 10-20 Mb 之间,我认为通过使用 gc.collect()
,结合限制并发实例请求的数量,会足以减少内存泄漏。我也知道 urllib2 只是 App Engine 的 urlfetch 的包装器,但提取不是问题,而是缩放。
变量f
占用多少内存?是否可以直接流式传输到 Google Cloud Storage,而不是先将数据加载到实例内存?
最佳答案
有一种方法,您可以直接从外部应用程序将数据写入 GCS,为此您必须将存储桶的 ACL 更改为公共(public),然后借助云存储 API 将数据写入存储桶.
此外,让我知道您是否遗漏了问题中有关自动缩放配置的任何详细信息。如果是,请详细说明。
关于python - 写入云存储时 GAE 内存泄漏,我可以流式传输吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28842256/