3

我有一个用于显示状态图像的 Sinatra 路由。虽然这个简单的解决方案有效,但我遇到了缓存问题:

get '/stream/:service/:stream_id.png' do
  # Building image_url omitted

  redirect image_url
end

在这里处理缓存以设置最大 TTL 的正确方法是什么?这些图像将嵌入其他站点,否则我可以直接链接到我重定向到的图像。

问题在于它会生成一个类似的 URL site.com/image.png,然后将其重定向到其他地方——但它site.com/image.png被浏览器认为是缓存的,因此它不会检查它是否已更新。

我已经对 Cache-Control 标头进行了一些试验,但我还没有找到解决方案。

如果这种方法完全愚蠢,我愿意接受其他解决方案。

4

2 回答 2

2

您基于每个路由设置 Cache-Control:

get '/stream/:service/:stream_id.png' do
  # Building image_url omitted
  response['Cache-Control'] = "public, max-age=0, must-revalidate"
  redirect image_url
end
于 2013-03-13T21:32:11.010 回答
0

你也可以使用 Sinatra 的expires方法:

# Set the Expires header and Cache-Control/max-age directive. Amount
# can be an integer number of seconds in the future or a Time object
# indicating when the response should be considered "stale". The remaining
# "values" arguments are passed to the #cache_control helper:
#
#   expires 500, :public, :must_revalidate
#   => Cache-Control: public, must-revalidate, max-age=60
#   => Expires: Mon, 08 Jun 2009 08:50:17 GMT

或者cache_control方法:

# Specify response freshness policy for HTTP caches (Cache-Control header).
# Any number of non-value directives (:public, :private, :no_cache,
# :no_store, :must_revalidate, :proxy_revalidate) may be passed along with
# a Hash of value directives (:max_age, :min_stale, :s_max_age).
#
#   cache_control :public, :must_revalidate, :max_age => 60
#   => Cache-Control: public, must-revalidate, max-age=60
#
# See RFC 2616 / 14.9 for more on standard cache control directives:
# http://tools.ietf.org/html/rfc2616#section-14.9.1

Sinatra 文档(截至 1.4.6 版本)

于 2015-07-09T00:53:33.520 回答