rails page caching (transgenic)

Has not quite sure what the original text at the place. The time being the oldest to find a time.
http://qbar.qq.com/pd4b5b1t/r/?86
http://www.railsenvy.com/2007/2/28/rails-caching-tutorial

For more information see:

http://www.ibm.com/developerworks/cn/web/wa-rails1/

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)
  end
   ...


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)
   end
   ...


"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 127.0.0.1 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 )
   # ...
end


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)
           expire_cache_for(post)
  end
  
  # If our sweeper detects that a Post was updated call this
  def after_update(post)
           expire_cache_for(post)
  end
  
  # If our sweeper detects that a Post was deleted call this
  def after_destroy(post)
           expire_cache_for(post)
  end
          
   private
  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)
  end
end


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>
    BalancerMember http://127.0.0.1:8030
   </Proxy>

   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
  RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
  RewriteRule ^/(.*)$ balancer://blog_cluster%{REQUEST_URI} [P,QSA,L]
   ...
</VirtualHost>


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]
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of rails page caching (transgenic)

  • Several good js calendar

    The first paragraph: js script /* alin */ /* Email:caoailin111@sohu.com */ /* QQ:38062022 */ /* Creation date: 2004-6-13 */ var myC_x,myC_y; var myC_timeset=null,myC_timeset1=null; var divObj=null; var inputName; function myCalendar() //Constructing an ob

  • JavaScript and jsp secondary structure linked the drop-down box without refresh

    Meeting (2005-10-25) finishing This article does not use Ajax technology, the use of a single deposit of JavaScript + Jsp + DHTML to achieve Paragraph keyword database table ID SuperID relations Select page to double Read data , achieve dynamic linked

  • Ruby will replace Java? I think not so soon

    I have heard a lot of such talk: Ruby On Rails (RoR) cool easy enough to prepare one In Web Application speed 10 times faster than Java, and it has some Java features not superior. By To, Ruby will replace Java to become the next generation of programming

  • Flying gems: the South American hummingbird and the Ruby programming language

    <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <meta name="ProgId" content="Word.Document"> <meta name = "Generator" content = " Microsoft Word 12 "> & ...

  • Pring Beanfactory at the jsp, servlet, web.xml and other configuration

    Keywords: spring beanfactory Spring in the web application called the Beanfactory 1) Configure web.xml Java code <? xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE web-app PUBLIC "- / / Sun Microsystems, Inc. / / ...

  • Can you understand programming you XP

    Agile Extreme Programming XP and RUP (ROSE provide large-scale software development "methodology") are two kinds of software development methodology. Great design is a use of all resources, from the entire field of thought to the design of ...

  • The performance of the seven best free antivirus software rankings

    Dr.Web, the full name of Dr.Web Antivirus for Windows, that is, Janice Fletcher "big spider," This is a Russian produced a powerful anti-virus anti-virus tools, using a new type of heuristic scanning methods to provide multi-level protectio ...

  • Pyronaridine listing! Ruby programming language

    Interactive Net Purchase Excellence Amazon purchase [Original title] The Ruby Programming Language Publishing ] [ O'Reilly Media, Inc. [Author] (United States) David Flanagan; Yukihiro Matsumoto Translator [] LIAO Zhi-gang; Zhang Wo [Name] Books O

  • RoR explained

    ROR is Ruby on Rails. Ruby is a well-known has been very good dynamic language It's dynamic language. Simple and easy. Dynamic languages are interpreted, but the performance may make a discount, but not absolute, because the application is complex, th

  • Servlet brief introduction

    Servlet brief introduction: Servlet is a small application server Are used to complete the B / S architecture, the client requests the response to treatment Platform independence, performance, able to run thread Servlet API for Servlet provides the s ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries