gpt4 book ai didi

ruby - 缓存获取的网页有哪些选项?

转载 作者:可可西里 更新时间:2023-11-01 16:38:35 27 4
gpt4 key购买 nike

我的应用会进行大量页面抓取,例如获取历史天气数据。获取特定页面后,我想将其缓存在我的 PostgreSQL 数据库中,这样我就不必为该特定请求再次访问远程服务器。

由于历史数据永远不会改变,我想“永远”缓存它们——这需要将缓存的页面存储在长期持久存储中,例如一个数据库。

我已经编写了一个围绕 Mechanize 的基本缓存机制。它有效,但似乎有比我更好的编码印章的人已经实现了这一点。

是否有任何 gem 或库已经这样做了?

最佳答案

所以我想了又想,并查看了 Mechanize 和 VCR 的源代码,我决定我真的只是想多了这个问题。以下工作非常适合我的需要。 (我使用的是 DataMapper,但将其转换为 ActiveRecord 模型会很简单):

class WebCache
include DataMapper::Resource

property :id, Serial
property :serialized_key, Text
property :serialized_value, Text
property :created_at, DateTime
property :updated_at, DateTime

def with_db_cache(akey)
serialized_key = YAML.dump(akey)
if (r = self.all(:serialized_key => serialized_key)).count != 0
# cache hit: return the de-serialized value
YAML.load(r.first.serialized_value)
else
# cache miss: evaluate the block, serialize and cache the result
yield(akey).tap {|avalue|
self.create(:serialized_key => serialized_key,
:serialized_value => YAML.dump(avalue))
}
end
end
end

示例用法:

def fetch(uri)
WebCache.with_db_cache(uri) {|uri|
# arrive here only on cache miss
Net::HTTP.get_response(URI(uri))
}
end

评论

我之前认为适当的 Web 缓存方案会观察和遵循 Cache-Control、If-Modified-Since 等 header 字段,并自动处理超时和其他 Web 病理。但是对实际网页的检查清楚地表明,真正的静态数据经常被标记为较短的缓存时间。因此,让调用者决定缓存内容的时间以及何时重试失败的查询更有意义。

到那时,代码变得非常简单。

道德:不要过度思考你的问题。

关于ruby - 缓存获取的网页有哪些选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14800921/

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