rails page caching (transgenic)

Has not quite sure what the original text at the place. The time being the oldest to find a time.

For more information see:


When you rise in web traffic, you may increase your number of cache rails application. This tutorial will tell you about all aspects of rails cache to help improve your rails application, and no longer excessive cpu overhead and bother.

rails cache has a number of ways, this tutorial will be divided into several parts separately introduce to you how to use a different cache program, as well as some of the advanced applications have targeted cache.

First of all, the introduction of the Cache Application Express: Page Caching, page caching

1, why should the cache
(If you have to understand the need for caching, you can skip this paragraph)
ruby is a kind of explanatory language, which means that in the absence of ruby code was executed before the machines are not compiled into the binary can be identified.
The characteristics and php is the same, but the java is totally different in this regard (java are first compiled into a binary, after the operation).
So, when someone visits your ruby program, you only read the code and implement, you can imagine, when the second hundred individuals have access to your code, your program will consume a lot of the system resources.
So how do we solve this changed?
(Translator: this article are discussed in the framework of the Rails caching mechanism, Ruby is the Rails framework for the development of a language, and java, c language the same.)

2, cache
Deal with are web cache (web application) in an important design strategy, which was placed in a temporary location. If someone requests a same application, we can provide him with a cached version of the application.
Provide a buffer, not only allows us to not read any of the application of database resources, and requests may be made without having to U.S. rails application services. (Translator: This is interesting to look back)
Designed at the beginning of the cache before the rails have some configuration settings required

3, cache configuration
Cache at the beginning of the application of the former, you need to configure your / config / environments / development.rb document

onfig.action_controller.perform_caching = true

By default, the cache mode in the product will be started, the above settings will be in the development environment to start the cache.

4, Page Caching, page caching
Page caching is the most rapid application of a cache. Well, at any time should the use of him?
1, for all users the same page
2, open the page, there is no user authentication page
If you have the applications meet the above conditions, please continue to read the following part. If your application does not, then please continue reading below to read more exciting (ps: I think the ads are the same all over the world, but is Depressed deyeb currently do not have a page in line with the above conditions , except 404 and 500 bar)

Assuming we are to design a blog system, the page does not often change, then we may well be that the controller to write:

class BlogController < ApplicationController
  def list
     Post.find(:all, :order => "created_on desc", :limit => 10)

Can see, List of this action is to query the most recent blog article 10, the corresponding web page will be displayed on the results of inquiries.
If we want to cache this page, then, simply;

class BlogController < ApplicationController
   caches_page :list
   def list
     Post.find(:all, :order => "created_on desc", :limit => 10)

"Caches_page" will be at the next request list this action, it will be html page content into a page, placed in a cache directory.

When you first run Mongrel in the code, visit this page, you will be in the / logs / development.log log log found in the following code:

Processing BlogController#list (for at 2007-02-23 00:58:56) [GET]
 Parameters: {"action"=>"list", "controller"=>"blog"}
SELECT * FROM posts ORDER BY created_on LIMIT 10
Rendering blog/list
Cached page: /blog/list.html (0.00000)
Completed in 0.18700 (5 reqs/sec) | Rendering: 0.10900 (58%) | DB: 0.00000 (0%) | 200 OK [http://localhost/blog/list]

Note this sentence: Cached page: / blog / list.htm,
This shows that this page has been loaded, and finally you see the html page has been stored in / public / blog / list.htm this location, if you check this page, you will find that there is no line above ruby code.

After the visit if it has the same url address, the load will be the html page, and does not reload the controller in action (Translator: say so more clearly). Imagine that a static page to load than the load, however, and explanatory language to deal with a much faster, almost up to 100 times faster! (Ps: This is true for large traffic in case of an effective solution, but also a very good general web design architecture.)

But only pay attention to or remind that such a static page is not to perform any ruby code. So that when your page some timely and necessary response to the user information, or current information, you should not use this page cache, instead of using the local cache. In the second part of this will have to explain.

Back to U.S. model,

caches_page :show

Do you think, when we visit one of a specific article, such as "/ blog/show/5", this page will be cached in the where?
The answer is here: / public/blog/show/5.html
The following examples illustrate the location of the cache page

http://localhost:3000/blog/list => /public/blog/list.html
http://localhost:3000/blog/edit/5 => /public/edit/5.html
http://localhost:3000/blog => /public/blog.html
http://localhost:3000/ => /public/index.html
http://localhost:3000/blog/list?page=2 => /public/blog/list.html

Note: the first line and last line of the cache files are the same, the page cache are ignored url address on the parameters.

5, how the cache of my page
In order to cache a different page, you need a different address. (Translated: I was crazy, did not expect this problem to continue and see) because when the page cache will be ignored like / blog / list? Page = 2 such a parameter, so you need to use / blog/list/2 such address forms, and found that we are using the id parameter values preserved, and now we need to use page to save the parameter values.
Now we modify / config / routes.rb document

map.connect 'blog/list/:page',
    :controller => 'blog',
    :action => 'list',
    :requirements => { :page => /\d+/},
    :page => nil

The use of a new definition of the routes, we should also be changed to link

<%= link_to "Next Page", :controller => 'blog', :action => 'list', :page => 2 %>

The results are finally connect "/ blog/list/2", when we point this connection, the background will deal with two things
1, application 2 Add page to this parameter, rather than the original id of this parameter
2, cache will generate / public/blog/list/2.html this page

Therefore, the cache page, it is necessary to the page parameters into a part of the page, and not to use the address parameter form, he is capable of being ignored.

6, clear the cache
After reading the contents of the above you may want to ask, if I have added a new article to the blog, how to refresh / blog / list of the action then?
To look at a few minutes ago we created / blog / list.html page, it does not contain the newly created us that the new article. In order to delete the cache, and generate a new cache, we need to let this page expired. For the above two pages are expired, we need to do:

# This will remove /blog/list.html
expire_page(:controller => 'blog', :action => 'list')

# This will remove /blog/show/5.html
expire_page(:controller => 'blog', :action => 'show', :id => 5)

It is obvious that we required in each implementation of the add, delete, modify the place to paste the code above, but there is a better way to solve the problem.
(Translator: Translation for the first time such a long article, written Can see U .S. ? ? Baidu Spaces published this article are the first, after the completion of reprinted in several places, we do so)

7, Sweepers, automatic cache clearing
sweepers is a cache automatically delete the old code. In order to achieve this function, sweepers required to track your models, the model when you change after the implementation of the additions and deletions, sweepers will be the implementation of the above orders.
sweepers can create your controllers directory, but I think he should be separated. You can / config / environment.rb. A to set :

Rails::Initializer.run do |config|
   # ...
    config.load_paths += %W( #{RAILS_ROOT}/app/sweepers )
   # ...

ps: remember to restart your service
In this way, you can at / app / sweepers created this directory of your sweepers. / app / sweepers / blog_sweeper.rb
Code can be written:

class BlogSweeper < ActionController::Caching::Sweeper
   observe Post # This sweeper is going to keep an eye on the Post model

  # If our sweeper detects that a Post was created call this
  def after_create(post)

  # If our sweeper detects that a Post was updated call this
  def after_update(post)

  # If our sweeper detects that a Post was deleted call this
  def after_destroy(post)

  def expire_cache_for(record)
    # Expire the list page now that we posted a new blog entry
     expire_page(:controller => 'blog', :action => 'list')

    # Also expire the show page, incase we just edited a blog entry
     expire_page(:controller => 'blog', :action => 'show', :id => record.id)

Tip: We can use the "after_save" alternative "after_create" and "after_update", yourself to try it!
We also need to tell the controller when we call the sweepers, so need to add in the controller:

class BlogController < ApplicationController
    caches_page :list, :show
   cache_sweeper :blog_sweeper, :only => [:create, :update, :destroy]

Well. We can try to add a new article, so logs / development.log: Medium You will find

Expired page: /blog/list.html (0.00000)
Expired page: /blog/show/3.html (0.00000)

U.S. sweepers have been working!
(Translator: This is the first essential of this article knowledge)

8, rails cache with Apache / lighttpd with the application (deyeb concern)
When we will be rails application to deploy to production environment, we are most used by apache server as the front rails Services will forward the request to the rails on rails server (Mongrel or Lighttpd). Since we use a cache static documents, so we need to tell apache server, service request page of the existence of a static cache and, if so, read the static files directly, without the request of the server rails. (Deyeb If it is such an easy design I )
httpd.conf configuration

<VirtualHost *:80>
  # Configure mongrel_cluster
   <Proxy balancer://blog_cluster>

   RewriteEngine On
   # Rewrite index to check for static
   RewriteRule ^/$ /index.html [QSA]

  # Rewrite to check for Rails cached page
  RewriteRule ^([^.]+)$ $1.html [QSA]

  # Redirect all non-static requests to cluster
  RewriteRule ^/(.*)$ balancer://blog_cluster%{REQUEST_URI} [P,QSA,L]

lighttpd configuration written

server.modules = ( "mod_rewrite", ... )
url.rewrite += ( "^/$" => "/index.html" )
url.rewrite += ( "^([^.]+)$" => "$1.html" )

Proxy server will see you placed in the / public directory of static files, but you may want to change the cache location in order to maintain independence. Would continue to watch the following introduction.

9, change your cache placement
First of all, necessary in your / config / environment.rb add the following code

config.action_controller.page_cache_directory = RAILS_ROOT + "/public/cache/"

This is you need to tell rails Services cache files will be placed in / public / cache the directory, you also need to rewrite the rules about httpd.conf.

  # Rewrite index to check for static
  RewriteRule ^/$ cache/index.html [QSA]

  # Rewrite to check for Rails cached page
  RewriteRule ^([^.]+)$ cache/$1.html [QSA]
分类:Ruby 时间:2009-03-28 人气:918
blog comments powered by Disqus


  • OSCache improve J2EE application performance-JSP tutorial system is running, J2EE/EJB / server 2010-08-26

    cache is used to improve the speed, improve system operating performance of the technology. Especially in web applications, by caching the output of the page can be very significant improvements in system operating performance. Introduction of this a

  • Common Web application security issues (1 - 4) (a) 2010-05-31

    After the two ("Web security issues of hierarchy" and "Understanding the essence of Web application security issues") on the Web security and Web application security conceptual knowledge of the macroscopic description, I believe we ha

  • Web application 2.0 features (1) 2015-01-27

    After you have built the initial version of a web application, it can be hard to know what to add in version 2.0, tricky to know how add value and make it expensive software , and near-impossible to understand what features a web 2.0 application actu

  • Configure the web application on the issue eclipse3.4 2010-03-29

    About eclipse3.4 configure web application problems: During this time the entry to the new company, the company you want to configure a project require is eclipse3.4, then an official in the eclipse under the net of a 3.4 version of the installation

  • Defined in server.xml a new WEB application 2010-05-26

    Modify server.xml, define a new WEB application The specific path to server.xml file as follows: D: \ Program Files \ Apache Software Foundation \ Tomcat 5.0 \ conf \ server.xml. The server.xml file the most is not the end </ Host> key insert a <

  • maven instance - a simple web application 2010-08-25

    1. Introduction Create a simple web application, and then will return to the serlvet container jetty to run this web application 2. Create a web application framework mvn archetype:generate-DgroupId=org.sonatype.mavenbook.ch05 -DartifactId=simple-web

  • google sitebricks learning experience - the most simple web application 2010-12-15

    Introduction Sitebricks is still in beta, it is a new Java ™ Web application framework. You may want to ask: "Why do I need another Web Framework?" Through Google Sitebricks, you can quickly build a maintenance or operation by another Web applic

  • 利用Web Application Stress Tool(WAS)做性能测试 2013-12-16

    Duwamish Online Aaron Ching, Pedro Silva, and Allen Wagner Microsoft Developer Network January 2001 摘要:这篇文章讨论了性能测试对于成功发布一个网络应用的重要性,集中讨论了微软的Web Application Stress (WAS)这个用于测试Duwamish Online的性能的工具. 内容 介绍 使用WAS的好处 WAS的缺陷 安装WAS 创建测试脚本 配置测试脚本 运行测试脚本 结论:最好

  • Web applications of the client cache 2011-07-17

    In today's web system, cache is every web system architect or developer must master the skills. The cache in the web world are generally divided into the client cache (of course, some people also call it the browser cache) and the server cache, the a

  • Web application framework with regard to the choice of technology Summary 2009-09-27

    Publisher: tomore Date :2007-11-23 14:11 Done recently in Web application framework and technology choice. We need to achieve the characteristics of a Web2.0 website Factors to consider: 1. Function modules (2-3 basic functions (release, reviews, pho

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 闽ICP备15018612号

processed in 0.346 (s). 12 q(s)