codecamp

Sinatra 缓存控制

要使用 HTTP 缓存,必须正确地设定消息头,幂等的 HTTP 动作可缓存。

你可以这样设定 Cache-Control 消息头:

get '/' do
  cache_control :public
  "cache it!"
end

核心提示: 在前置过滤器中设定缓存。

before do
  cache_control :public, :must_revalidate, :max_age => 60
end

如果你正在用 expires 辅助方法设定对应的消息头 Cache-Control 会自动设定:

before do
  expires 500, :public, :must_revalidate
end

为了合适地使用缓存,你应该考虑使用 ​etag​ 和 ​last_modified​ 方法。推荐在执行繁重任务之前使用这些 helpers,这样一来,如果客户端在缓存中已经有相关内容,就会立即得到显示。

get '/article/:id' do
  @article = Article.find params[:id]
  last_modified @article.updated_at
  etag @article.sha1
  erb :article
end

使用 weak ETag 也是有可能的:

etag @article.sha1, :weak 

这些辅助方法并不会为你做任何缓存,而是将必要的信息传送给你的缓存 如果你在寻找缓存的快速解决方案,试试 rack-cache:

require "rack/cache"
require "sinatra"

use Rack::Cache

get '/' do
  cache_control :public, :max_age => 36000
  sleep 5
  "hello"
end


Sinatra 浏览器重定向
Sinatra 发送文件
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Sinatra 配置

Sinatra 错误处理

Sinatra Sinatra::Base - 中间件,程序库和模块化应用

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }