首页 > 解决方案 > 在 open-uri 中禁用缓存

问题描述

遗憾的是,当数据发生变化时,我不得不轮询一个端点并更新另一个系统。我写了一个循环(有一个sleep语句,所以我不 DOS 服务器):

require 'nokogiri'
require 'open-uri'

desired_data = 'foo'
data = nil
url = nil

while data != desired_data do
  sleep(2)
  url = "https://elections.wi.gov/index.php/elections-voting/statistics"
  doc = Nokogiri::HTML.parse(open(url))

  puts doc

  # do some nokogiri stuff to extract the information I want.

  # store information to `data` variable.
end

# if control is here it means the data changed

这工作正常,除非服务器更新时open(url)仍然返回旧内容(即使我重新启动脚本)。

似乎可能有一些缓存在起作用。如何禁用它?

以下是返回的 HTTP 标头:

HTTP/2 200
date: Fri, 02 Oct 2020 14:00:44 GMT
content-type: text/html; charset=UTF-8
set-cookie: __cfduid=dd8fca84d468814dd199dfc08d45c98831601647244; expires=Sun, 01-Nov-20 14:00:44 GMT; path=/; domain=.elections.wi.gov; HttpOnly; SameSite=Lax; Secure
x-powered-by: PHP/7.2.24
cache-control: max-age=3600, public
x-drupal-dynamic-cache: MISS
link: <https://elections.wi.gov/index.php/elections-voting/statistics>; rel="canonical"
x-ua-compatible: IE=edge
content-language: en
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
expires: Sun, 19 Nov 1978 05:00:00 GMT
last-modified: Fri, 02 Oct 2020 12:47:38 GMT
vary: Cookie
x-generator: Drupal 8 (https://www.drupal.org)
x-drupal-cache: HIT
x-speed-cache: HIT
x-speed-cache-key: /index.php/elections-voting/statistics
x-nocache: Cache
x-this-proto: https
x-server-name: elections.wi.gov
access-control-allow-origin: *
x-xss-protection: 1; mode=block
cache-control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
cf-cache-status: DYNAMIC
cf-request-id: 058b368b9f00002ff234177200000001
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
cf-ray: 5dbef38c3b6a2ff2-ORD```

If it matters, I’m using Ruby 2.7 on macOS Big Sur. 

标签: rubyopen-uri

解决方案


这可能是 Drupal 8 网站本身的问题,因为它有自己的缓存管理器 - 如果您使用 Web 浏览器有新内容,似乎每个用户都有一个缓存。

很容易看出某个页面因哪些缓存上下文而异,以及哪些缓存标记因它而无效:必须只查看 X-Drupal-Cache-Contexts 和 X-Drupal-Cache-Tags 标头!

但是这些标题在您的列表中不可用。如果您与网站的开发人员保持联系,请要求他们执行以下操作:

您可以通过在 services.yml 中将 http.response.debug_cacheability_headers 容器参数设置为 true 来调试可缓存响应(实现此接口的响应,可能由页面缓存或动态页面缓存缓存)。随后是容器重建,这在更改容器参数时是必需的。

这将导致 Drupal 发送 X-Drupal-Cache-Tags、X-Drupal-Cache-Contexts 标头。


推荐阅读