简体   繁体   English

如何在轨道上的ruby中启用背景图像的缓存?

[英]How to enable caching of background images in ruby on rails?

How can I cache background images (forcefully) in user's browser. 如何在用户的浏览器中(强制)缓存背景图像。 It will great to set a expiry time of 1 week or 1 month something. 设置1周或1个月的到期时间会很棒。

PS:I have a page which shows listing based upon category. PS:我有一个页面,显示基于类别的列表。 Every category has its own background image and I want to cache those background images.Every image is something about 20-30kb and I have some 20 categories. 每个类别都有自己的背景图片,我想缓存那些背景图片。每个图片大约20-30kb,我有20个类别。

Varnish is a solution and here is the gem which can help you in implementing it Varnish是一个解决方案, 这里的宝石可以帮助您实现它

Install This gem requires ruby 1.9 安装此gem需要ruby 1.9

Basic installation 基本安装

sudo gem install lacquer  
rails generate lacquer:install

config/initializers/lacquer.rb 配置/初始化/ lacquer.rb

Lacquer.configure do |config|
  # Globally enable/disable cache
  config.enable_cache = true

  # Unless overridden in a controller or action, the default will be used
  config.default_ttl = 1.week

  # Can be :none, :delayed_job, :resque
  config.job_backend = :none

  # Array of Varnish servers to manage
  config.varnish_servers << {
    :host => "0.0.0.0", :port => 6082 # if you have authentication enabled, add :secret => "your secret"
  }

  # Number of retries
  config.retries = 5

  # config handler (optional, if you use Hoptoad or another error tracking service)
  config.command_error_handler = lambda { |s| HoptoadNotifier.notify(s) }

  ### Varnish - 2.x  /  3.x  .. VCL-Changes
  ### https://www.varnish-cache.org/docs/trunk/installation/upgrade.html

  # => Purge Command  ( "url.purge" for Varnish 2.x .. "ban.url" for Varnish 3.x )
  # => purges are now called bans in Varnish 3.x .. purge() and purge_url() are now respectively ban() and ban_url()
  config.purge_command = "ban.url"

  # => VCL_Fetch Pass Command  ( "pass" for Varnish 2.x .. "hit_for_pass" for Varnish 3.x )
  # => pass in vcl_fetch renamed to hit_for_pass in Varnish 3.x   
  config.pass_command = "pass"
end

app/controllers/application_controller.rb 应用程序/控制器/ application_controller.rb

class ApplicationController < ActionController::Base
  include Lacquer::CacheUtils
end

config/varnishd.yml 配置/ varnishd.yml

development:
  listen: localhost:3001
  telnet: localhost:6082
  sbin_path: /usr/local/sbin
  storage: "file,#{Rails.root}/log/varnishd.#{Rails.env}.cache,100MB"

test:
  listen: localhost:3002
  telnet: localhost:6083
  sbin_path: /usr/local/sbin
  storage: "file,#{Rails.root}/log/varnishd.#{Rails.env}.cache,100MB"

production:
  listen: :80
  telnet: localhost:6082
  sbin_path: /usr/local/sbin
  storage: "file,#{Rails.root}/log/varnishd.#{Rails.env}.cache,100MB"
  params:
    overflow_max: 2000          # for Varnish 2.x ... use "queue_max: 2000" for Varnish 3.x
    thread_pool_add_delay: 2
    thread_pools: 4             # <Number of cpu cores>
    thread_pool_min: 200        # <800/number of cpu cores>
    thread_pool_max: 4000

If only some urls of the application should be cached by varnish, Lacquer::CacheControl will be helpful. 如果清漆仅缓存应用程序的某些URL,Lacquer :: CacheControl将很有帮助。

config/initializers/caches.rb 配置/初始化/ caches.rb

require "lacquer/cache_control"

Lacquer.cache_control.configure do |config|
  config.register :static,              :url => "^/images",                                           
                                        :expires_in => "365d"

  config.register :static,              :url => "^/stylesheets",
                                        :expires_in => "365d"

  config.register :static,              :url => "^/javascripts",                                       
                                        :expires_in => "365d"

  config.register :class_section,       :url => "^(/[a-z]{2})?/(info_screens|class_sections)/%s.*$",   
                                        :args => "[0-9]+", 
                                        :expires_in => "1m"

  config.register :open_scoring,        :url => "^(/[a-z]{2})?/class_sections/%s/open_scoring.*$",
                                        :args => "[0-9]+",
                                        :expires_in => "1m"

end

In the sweeper we can do something like this 在扫地机中我们可以做这样的事情

class_section = ClassSection.find(1)
Lacquer.cache_control.purge(:open_scoring, class_section)

This will purge “^(/[az]{2})?/class_sections/1/open_scoring.*$” (/sv/class_sections/1/open_scoring.js, /sv/class_sections/1/open_scoring.html) 这将清除“ ^(/ [az] {2})?/ class_sections / 1 / open_scoring。* $”(/sv/class_sections/1/open_scoring.js,/sv/class_sections/1/open_scoring.html)

The varnish.vcl is preprocssed when starting varnishd with the rake tasks 当使用rake任务启动varnishd时,varnish.vcl是预处理的

rake lacquer:varnishd:start

config/varnish.vcl.erb 配置/ varnish.vcl.erb

sub vcl_recv {
  # Lookup requests that we know should be cached
  if (<%= Lacquer.cache_control.to_vcl_conditions %>) {    
    # Clear cookie and authorization headers, set grace time, lookup in the cache
    unset req.http.Cookie;
    unset req.http.Authorization;
    return(lookup);
  }

  # Generates
  #
  # if(req.url ~ "^/images" || 
  #    req.url ~ "^/stylesheets" || 
  #    req.url ~ "^/javascripts" || 
  #    req.url ~ "^(/[a-z]{2})?/(info_screens|class_sections)/[0-9]+.*$" || 
  #    req.url ~ "^(/[a-z]{2})?/class_sections/[0-9]+/open_scoring.*$") {
  #    unset req.http.Cookie;
  #    unset req.http.Authorization;
  #    return(lookup);         
  # }
}

sub vcl_fetch {
  <%= Lacquer.cache_control.to_vcl_override_ttl_urls %>

  # Generates
  #
  # if(req.url ~ "^/images" || req.url ~ "^/stylesheets" || req.url ~ "^/javascripts") {
  #   unset beresp.http.Set-Cookie;
  #   set beresp.ttl = 365d;
  #   return(deliver);
  # }
  #
  # if(req.url ~ "^(/[a-z]{2})?/(info_screens|class_sections)/[0-9]+.*$" || 
  #   req.url ~ "^(/[a-z]{2})?/class_sections/[0-9]+/open_scoring.*$") {
  #   unset beresp.http.Set-Cookie;
  #   set beresp.ttl = 1m;
  #   return(deliver);
  # }
}

This makes it much simpler to perform cacheing, it's only setuped in one place, purge it or just let it expire. 这使得执行缓存变得更加简单,它只在一个地方设置,清除它或只是让它过期。

Usage To set a custom ttl for a controller: 用法为控制器设置自定义ttl:

  before_filter { |controller| controller.set_cache_ttl(15.minutes) }

Clearing the cache: 清除缓存:

class Posts < ApplicationController
  after_filter :clear_cache, :only => [ :create, :update, :destroy ]

private

  def clear_cache
    clear_cache_for(
      root_path,
      posts_path,
      post_path(@post))
  end
end

Control varnishd with the following rake tasks 通过以下rake任务对控件进行清漆

rake lacquer:varnishd:start
rake lacquer:varnishd:stop
rake lacquer:varnishd:restart
rake lacquer:varnishd:status
rake lacquer:varnishd:global_purge

Gotchas The default TTL for most actions is set to 0, since for most cases you'll probably want to be fairly explicit about what pages do get cached by varnish. 陷阱大多数操作的默认TTL设置为0,因为在大多数情况下,您可能想相当清楚地知道清漆会缓存哪些页面。 The default cache header is typically: 默认缓存标头通常是:

Cache-Control: max-age=0, no-cache, private This is good for normal controller actions, since you won't want to cache them. 高速缓存控制:max-age = 0,无高速缓存,专用这对于常规的控制器操作非常有用,因为您不想对其进行高速缓存。 If TTL for an action is set to 0, it won't mess with the default header. 如果将某个操作的TTL设置为0,则不会与默认标头混淆。

The key gotcha here is that cached pages strip cookies, so if your application relies on sessions and uses authenticity tokens, the user will need a session cookie set before form actions will work. 这里的关键是缓存页面剥离cookie,因此如果您的应用程序依赖于会话并使用真实性令牌,则用户将需要在表单操作起作用之前设置会话cookie。 Setting default TTL to 0 here will make sure these session cookies won't break. 在此处将默认TTL设置为0将确保这些会话cookie不会中断。

As a result, all you have to do to set a cacheable action is the before filter above. 因此,设置可缓存操作所需要做的就是上面的前置过滤器。

在我工作的地方,我们用清漆做这类东西。

If you're using the asset pipeline of rails 3.1, rails is already adding the necessary cache control headers for you. 如果您正在使用Rails 3.1的资产管道,则Rails已经为您添加了必要的缓存控制标头。 This means images are cached by the client. 这意味着客户端会缓存图像。 Rails also makes sure the filename changes after a redeploy, so visitors don't see the old images that are still in their cache. Rails还确保在重新部署后文件名发生更改,因此访问者不会看到仍在其缓存中的旧图像。

See also: http://guides.rubyonrails.org/asset_pipeline.html#live-compilation 另见: http//guides.rubyonrails.org/asset_pipeline.html#live-compilation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM