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]
分类:Ruby 时间:2009-03-28 人气:717
分享到:
blog comments powered by Disqus

相关文章

  • 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

  • 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 ...

  • 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, t

  • 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 ...

  • MVC architecture based on design-PHP Web Application System 2010-10-08

    Abstract: Analysis of the MVC software model described by a language based on PHP XML and XSL technology combined with the MVC framework for discussion of the MVC design pattern instance of the design method. Keywords: MVC model view controller architectu

  • Large-scale dynamic web application system architecture design 2011-02-22

    http://www.y513.com/201010658.html Large dynamic application platform is mainly aimed at high-volume, high concurrency site to establish the underlying system architecture. Large-scale operation of the site needs a reliable, secure, scalable, maintainable

  • Management of a Web application static resources, recruit fresh 2010-01-07

    Web development, there would always need to modify the CSS path for a static resource, such as images. If the huge amount of resources, we need to replace a lot of repetitive work, so that is also prone to error. At this time, think of Groovy in the ...

  • Tomcat web application deployment 2010-11-06

    Max on us today about web training program in the proper deployment under tomcat. Mainly include: 1.java the classloader in tomcat architecture under http://www.jaxmao.org/tomcat-docs/class-loader-howto.html Wrote Like many server applications, like, Tomc

  • [Reserved] crazy big collection of Web application open source project 2011-08-17

    <p mce_style="text-align: left; "> switched http://coolshell.cn/articles/5132.html <br> <br> <br> The following is a list of open-source Web applications . Nothing to say, crazy. In particular, it is a bunch of Web 2.0. I

  • Using struts + spring + hibernate web application assembly 2010-04-01

    This article will discuss how the combination of several well-known framework to achieve the purpose of loose coupling, how to build your framework, how to make you be consistent in all the application layer. Challenging is: the combination of these frame

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

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

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.428 (s). 14 q(s)