-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaching_with_rails.html
586 lines (529 loc) · 40.3 KB
/
caching_with_rails.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Caching with Rails: An overview — Ruby on Rails 指南</title>
<meta name="description" content="Ruby on Rails 指南:系統學習 Rails(Rails 4.2 版本)" >
<meta name="keywords" content="Ruby on Rails Guides 指南 中文 學習 免費 網路 Web 開發" >
<meta name="author" content="http://git.io/G_R1sA">
<meta property="fb:admins" content="1340181291">
<meta property="og:title" content="Caching with Rails: An overview — Ruby on Rails 指南" >
<meta property="og:site_name" content="Ruby on Rails 指南">
<meta property="og:image" content="http://rails.ruby.tw/images/rails_guides_cover.jpg">
<meta property="og:url" content="http://rails.ruby.tw/">
<meta property="og:type" content="article">
<meta property="og:description" content="Ruby on Rails 指南:系統學習 Rails(Rails 4.2 版本)">
<link rel="stylesheet" href="stylesheets/application.css">
<link href="http://fonts.googleapis.com/css?family=Noto+Sans:400,700|Noto+Serif:700|Source+Code+Pro" rel="stylesheet">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon">
</head>
<body class="guide">
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/zh-TW/sdk.js#xfbml=1&appId=837401439623727&version=v2.0";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<script type="text/javascript">
window.twttr=(function(d,s,id){var t,js,fjs=d.getElementsByTagName(s)[0];if(d.getElementById(id)){return}js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);return window.twttr||(t={_e:[],ready:function(f){t._e.push(f)}})}(document,"script","twitter-wjs"));
</script>
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">更多內容 <a href="http://rubyonrails.org/">rubyonrails.org:</a></strong>
<span class="red-button more-info-button">
更多內容
</span>
<ul class="more-info-links s-hidden">
<li class="more-info"><a href="http://rubyonrails.org/">綜覽</a></li>
<li class="more-info"><a href="http://rubyonrails.org/download">下載</a></li>
<li class="more-info"><a href="http://rubyonrails.org/deploy">部署</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">原始碼</a></li>
<li class="more-info"><a href="http://rubyonrails.org/screencasts">影片</a></li>
<li class="more-info"><a href="http://rubyonrails.org/documentation">文件</a></li>
<li class="more-info"><a href="http://rubyonrails.org/community">社群</a></li>
<li class="more-info"><a href="http://weblog.rubyonrails.org/">Blog</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="回首頁">Guides.rubyonrails.org</a></h1>
<ul class="nav">
<li><a class="nav-item" href="index.html">首頁</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">指南目錄</a>
<div id="guides" class="clearfix" style="display: none;">
<hr>
<dl class="L">
<dt>起步走</dt>
<dd><a href="getting_started.html">Rails 起步走</a></dd>
<dt>Models</dt>
<dd><a href="active_record_basics.html">Active Record 基礎</a></dd>
<dd><a href="active_record_migrations.html">Active Record 遷移</a></dd>
<dd><a href="active_record_validations.html">Active Record 驗證</a></dd>
<dd><a href="active_record_callbacks.html">Active Record 回呼</a></dd>
<dd><a href="association_basics.html">Active Record 關聯</a></dd>
<dd><a href="active_record_querying.html">Active Record 查詢</a></dd>
<dt>Views</dt>
<dd><a href="layouts_and_rendering.html">Rails 算繪與版型</a></dd>
<dd><a href="form_helpers.html">Action View 表單輔助方法</a></dd>
<dt>Controllers</dt>
<dd><a href="action_controller_overview.html">Action Controller 綜覽</a></dd>
<dd><a href="routing.html">Rails 路由:深入淺出</a></dd>
</dl>
<dl class="R">
<dt>深入了解</dt>
<dd><a href="active_support_core_extensions.html">Active Support 核心擴展</a></dd>
<dd><a href="i18n.html">Rails 國際化 API</a></dd>
<dd><a href="action_mailer_basics.html">Action Mailer 基礎</a></dd>
<dd><a href="active_job_basics.html">Active Job 基礎</a></dd>
<dd><a href="security.html">Rails 安全指南</a></dd>
<dd><a href="debugging_rails_applications.html">除錯 Rails 應用程式</a></dd>
<dd><a href="configuring.html">Rails 應用程式設定</a></dd>
<dd><a href="command_line.html">Rake 任務與 Rails 命令列工具</a></dd>
<dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
<dd><a href="working_with_javascript_in_rails.html">在 Rails 使用 JavaScript</a></dd>
<dd><a href="constant_autoloading_and_reloading.html">Constant Autoloading and Reloading</a></dd>
<dt>擴充 Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">客製與新建 Rails 產生器</a></dd>
<dd><a href="rails_application_templates.html">Rails 應用程式模版</a></dd>
<dt>貢獻 Ruby on Rails</dt>
<dd><a href="contributing_to_ruby_on_rails.html">貢獻 Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API 文件準則</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails 指南準則</a></dd>
<dt>維護方針</dt>
<dd><a href="maintenance_policy.html">維護方針</a></dd>
<dt>發佈記</dt>
<dd><a href="upgrading_ruby_on_rails.html">升級 Ruby on Rails</a></dd>
<dd><a href="4_2_release_notes.html">Ruby on Rails 4.2 發佈記</a></dd>
<dd><a href="4_1_release_notes.html">Ruby on Rails 4.1 發佈記</a></dd>
<dd><a href="4_0_release_notes.html">Ruby on Rails 4.0 發佈記</a></dd>
<dd><a href="3_2_release_notes.html">Ruby on Rails 3.2 發佈記</a></dd>
<dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 發佈記</a></dd>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 發佈記</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 發佈記</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 發佈記</a></dd>
<dt>Rails 指南翻譯術語</dt>
<dd><a href="translation_terms.html">翻譯術語</a></dd>
</dl>
</div>
</li>
<li><a class="nav-item" href="//github.com/docrails-tw/guides">貢獻翻譯</a></li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">貢獻</a></li>
<li><a class="nav-item" href="credits.html">致謝</a></li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">指南目錄</option>
<optgroup label="起步走">
<option value="getting_started.html">Rails 起步走</option>
</optgroup>
<optgroup label="Models">
<option value="active_record_basics.html">Active Record 基礎</option>
<option value="active_record_migrations.html">Active Record 遷移</option>
<option value="active_record_validations.html">Active Record 驗證</option>
<option value="active_record_callbacks.html">Active Record 回呼</option>
<option value="association_basics.html">Active Record 關聯</option>
<option value="active_record_querying.html">Active Record 查詢</option>
</optgroup>
<optgroup label="Views">
<option value="layouts_and_rendering.html">Rails 算繪與版型</option>
<option value="form_helpers.html">Action View 表單輔助方法</option>
</optgroup>
<optgroup label="Controllers">
<option value="action_controller_overview.html">Action Controller 綜覽</option>
<option value="routing.html">Rails 路由:深入淺出</option>
</optgroup>
<optgroup label="深入了解">
<option value="active_support_core_extensions.html">Active Support 核心擴展</option>
<option value="i18n.html">Rails 國際化 API</option>
<option value="action_mailer_basics.html">Action Mailer 基礎</option>
<option value="active_job_basics.html">Active Job 基礎</option>
<option value="security.html">Rails 安全指南</option>
<option value="debugging_rails_applications.html">除錯 Rails 應用程式</option>
<option value="configuring.html">Rails 應用程式設定</option>
<option value="command_line.html">Rake 任務與 Rails 命令列工具</option>
<option value="asset_pipeline.html">Asset Pipeline</option>
<option value="working_with_javascript_in_rails.html">在 Rails 使用 JavaScript</option>
<option value="constant_autoloading_and_reloading.html">Constant Autoloading and Reloading</option>
</optgroup>
<optgroup label="擴充 Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">客製與新建 Rails 產生器</option>
<option value="rails_application_templates.html">Rails 應用程式模版</option>
</optgroup>
<optgroup label="貢獻 Ruby on Rails">
<option value="contributing_to_ruby_on_rails.html">貢獻 Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API 文件準則</option>
<option value="ruby_on_rails_guides_guidelines.html">Ruby on Rails 指南準則</option>
</optgroup>
<optgroup label="維護方針">
<option value="maintenance_policy.html">維護方針</option>
</optgroup>
<optgroup label="發佈記">
<option value="upgrading_ruby_on_rails.html">升級 Ruby on Rails</option>
<option value="4_2_release_notes.html">Ruby on Rails 4.2 發佈記</option>
<option value="4_1_release_notes.html">Ruby on Rails 4.1 發佈記</option>
<option value="4_0_release_notes.html">Ruby on Rails 4.0 發佈記</option>
<option value="3_2_release_notes.html">Ruby on Rails 3.2 發佈記</option>
<option value="3_1_release_notes.html">Ruby on Rails 3.1 發佈記</option>
<option value="3_0_release_notes.html">Ruby on Rails 3.0 發佈記</option>
<option value="2_3_release_notes.html">Ruby on Rails 2.3 發佈記</option>
<option value="2_2_release_notes.html">Ruby on Rails 2.2 發佈記</option>
</optgroup>
<optgroup label="Rails 指南翻譯術語">
<option value="translation_terms.html">翻譯術語</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
</div>
<hr class="hide">
<div id="feature">
<div class="wrapper">
<h2>Caching with Rails: An overview</h2><p>This guide will teach you what you need to know about avoiding that expensive round-trip to your database and returning what you need to return to the web clients in the shortest time possible.</p><p>After reading this guide, you will know:</p>
<ul>
<li>Page and action caching (moved to separate gems as of Rails 4).</li>
<li>Fragment caching.</li>
<li>Alternative cache stores.</li>
<li>Conditional GET support.</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li>
<a href="#basic-caching">Basic Caching</a>
<ul>
<li><a href="#page-caching">Page Caching</a></li>
<li><a href="#action-caching">Action Caching</a></li>
<li><a href="#fragment-caching">Fragment Caching</a></li>
<li><a href="#low-level-caching">Low-Level Caching</a></li>
<li><a href="#sql-caching">SQL Caching</a></li>
</ul>
</li>
<li>
<a href="#cache-stores">Cache Stores</a>
<ul>
<li><a href="#configuration">Configuration</a></li>
<li><a href="#activesupport-cache-store">ActiveSupport::Cache::Store</a></li>
<li><a href="#activesupport-cache-memorystore">ActiveSupport::Cache::MemoryStore</a></li>
<li><a href="#activesupport-cache-filestore">ActiveSupport::Cache::FileStore</a></li>
<li><a href="#activesupport-cache-memcachestore">ActiveSupport::Cache::MemCacheStore</a></li>
<li><a href="#activesupport-cache-ehcachestore">ActiveSupport::Cache::EhcacheStore</a></li>
<li><a href="#activesupport-cache-nullstore">ActiveSupport::Cache::NullStore</a></li>
<li><a href="#custom-cache-stores">Custom Cache Stores</a></li>
<li><a href="#cache-keys">Cache Keys</a></li>
</ul>
</li>
<li><a href="#conditional-get-support">Conditional GET support</a></li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="basic-caching">1 Basic Caching</h3><p>This is an introduction to three types of caching techniques: page, action and
fragment caching. Rails provides by default fragment caching. In order to use
page and action caching, you will need to add <code>actionpack-page_caching</code> and
<code>actionpack-action_caching</code> to your Gemfile.</p><p>To start playing with caching you'll want to ensure that <code>config.action_controller.perform_caching</code> is set to <code>true</code>, if you're running in development mode. This flag is normally set in the corresponding <code>config/environments/*.rb</code> and caching is disabled by default for development and test, and enabled for production.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.action_controller.perform_caching = true
</pre>
</div>
<h4 id="page-caching">1.1 Page Caching</h4><p>Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver (i.e. Apache or NGINX), without ever having to go through the Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with.</p><div class="info"><p>Page Caching has been removed from Rails 4. See the <a href="https://github.com/rails/actionpack-page_caching">actionpack-page_caching gem</a>. See <a href="http://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works">DHH's key-based cache expiration overview</a> for the newly-preferred method.</p></div><h4 id="action-caching">1.2 Action Caching</h4><p>Page Caching cannot be used for actions that have before filters - for example, pages that require authentication. This is where Action Caching comes in. Action Caching works like Page Caching except the incoming web request hits the Rails stack so that before filters can be run on it before the cache is served. This allows authentication and other restrictions to be run while still serving the result of the output from a cached copy.</p><div class="info"><p>Action Caching has been removed from Rails 4. See the <a href="https://github.com/rails/actionpack-action_caching">actionpack-action_caching gem</a>. See <a href="http://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works">DHH's key-based cache expiration overview</a> for the newly-preferred method.</p></div><h4 id="fragment-caching">1.3 Fragment Caching</h4><p>Life would be perfect if we could get away with caching the entire contents of a page or action and serving it out to the world. Unfortunately, dynamic web applications usually build pages with a variety of components not all of which have the same caching characteristics. In order to address such a dynamically created page where different parts of the page need to be cached and expired differently, Rails provides a mechanism called Fragment Caching.</p><p>Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.</p><p>As an example, if you wanted to show all the orders placed on your website in real time and didn't want to cache that part of the page, but did want to cache the part of the page which lists all products available, you could use this piece of code:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<% Order.find_recent.each do |o| %>
<%= o.buyer.name %> bought <%= o.product.name %>
<% end %>
<% cache do %>
All available products:
<% Product.all.each do |p| %>
<%= link_to p.name, product_url(p) %>
<% end %>
<% end %>
</pre>
</div>
<p>The cache block in our example will bind to the action that called it and is written out to the same place as the Action Cache, which means that if you want to cache multiple fragments per action, you should provide an <code>action_suffix</code> to the cache call:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<% cache(action: 'recent', action_suffix: 'all_products') do %>
All available products:
</pre>
</div>
<p>and you can expire it using the <code>expire_fragment</code> method, like so:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
expire_fragment(controller: 'products', action: 'recent', action_suffix: 'all_products')
</pre>
</div>
<p>If you don't want the cache block to bind to the action that called it, you can also use globally keyed fragments by calling the <code>cache</code> method with a key:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% cache('all_available_products') do %>
All available products:
<% end %>
</pre>
</div>
<p>This fragment is then available to all actions in the <code>ProductsController</code> using the key and can be expired the same way:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
expire_fragment('all_available_products')
</pre>
</div>
<p>If you want to avoid expiring the fragment manually, whenever an action updates a product, you can define a helper method:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module ProductsHelper
def cache_key_for_products
count = Product.count
max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number)
"products/all-#{count}-#{max_updated_at}"
end
end
</pre>
</div>
<p>This method generates a cache key that depends on all products and can be used in the view:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% cache(cache_key_for_products) do %>
All available products:
<% end %>
</pre>
</div>
<p>If you want to cache a fragment under certain condition you can use <code>cache_if</code> or <code>cache_unless</code></p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% cache_if (condition, cache_key_for_products) do %>
All available products:
<% end %>
</pre>
</div>
<p>You can also use an Active Record model as the cache key:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% Product.all.each do |p| %>
<% cache(p) do %>
<%= link_to p.name, product_url(p) %>
<% end %>
<% end %>
</pre>
</div>
<p>Behind the scenes, a method called <code>cache_key</code> will be invoked on the model and it returns a string like <code>products/23-20130109142513</code>. The cache key includes the model name, the id and finally the updated_at timestamp. Thus it will automatically generate a new fragment when the product is updated because the key changes.</p><p>You can also combine the two schemes which is called "Russian Doll Caching":</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% cache(cache_key_for_products) do %>
All available products:
<% Product.all.each do |p| %>
<% cache(p) do %>
<%= link_to p.name, product_url(p) %>
<% end %>
<% end %>
<% end %>
</pre>
</div>
<p>It's called "Russian Doll Caching" because it nests multiple fragments. The advantage is that if a single product is updated, all the other inner fragments can be reused when regenerating the outer fragment.</p><h4 id="low-level-caching">1.4 Low-Level Caching</h4><p>Sometimes you need to cache a particular value or query result, instead of caching view fragments. Rails caching mechanism works great for storing <strong>any</strong> kind of information.</p><p>The most efficient way to implement low-level caching is using the <code>Rails.cache.fetch</code> method. This method does both reading and writing to the cache. When passed only a single argument, the key is fetched and value from the cache is returned. If a block is passed, the result of the block will be cached to the given key and the result is returned.</p><p>Consider the following example. An application has a <code>Product</code> model with an instance method that looks up the product’s price on a competing website. The data returned by this method would be perfect for low-level caching:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Product < ActiveRecord::Base
def competing_price
Rails.cache.fetch("#{cache_key}/competing_price", expires_in: 12.hours) do
Competitor::API.find_price(id)
end
end
end
</pre>
</div>
<div class="note"><p>Notice that in this example we used <code>cache_key</code> method, so the resulting cache-key will be something like <code>products/233-20140225082222765838000/competing_price</code>. <code>cache_key</code> generates a string based on the model’s <code>id</code> and <code>updated_at</code> attributes. This is a common convention and has the benefit of invalidating the cache whenever the product is updated. In general, when you use low-level caching for instance level information, you need to generate a cache key.</p></div><h4 id="sql-caching">1.5 SQL Caching</h4><p>Query caching is a Rails feature that caches the result set returned by each query so that if Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.</p><p>For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ApplicationController
def index
# Run a find query
@products = Product.all
...
# Run the same query again
@products = Product.all
end
end
</pre>
</div>
<h3 id="cache-stores">2 Cache Stores</h3><p>Rails provides different stores for the cached data created by <strong>action</strong> and <strong>fragment</strong> caches.</p><div class="info"><p>Page caches are always stored on disk.</p></div><h4 id="configuration">2.1 Configuration</h4><p>You can set up your application's default cache store by calling <code>config.cache_store=</code> in the Application definition inside your <code>config/application.rb</code> file or in an Application.configure block in an environment specific configuration file (i.e. <code>config/environments/*.rb</code>). The first argument will be the cache store to use and the rest of the argument will be passed as arguments to the cache store constructor.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.cache_store = :memory_store
</pre>
</div>
<div class="note"><p>Alternatively, you can call <code>ActionController::Base.cache_store</code> outside of a configuration block.</p></div><p>You can access the cache by calling <code>Rails.cache</code>.</p><h4 id="activesupport-cache-store">2.2 ActiveSupport::Cache::Store</h4><p>This class provides the foundation for interacting with the cache in Rails. This is an abstract class and you cannot use it on its own. Rather you must use a concrete implementation of the class tied to a storage engine. Rails ships with several implementations documented below.</p><p>The main methods to call are <code>read</code>, <code>write</code>, <code>delete</code>, <code>exist?</code>, and <code>fetch</code>. The fetch method takes a block and will either return an existing value from the cache, or evaluate the block and write the result to the cache if no value exists.</p><p>There are some common options used by all cache implementations. These can be passed to the constructor or the various methods to interact with entries.</p>
<ul>
<li><p><code>:namespace</code> - This option can be used to create a namespace within the cache store. It is especially useful if your application shares a cache with other applications.</p></li>
<li><p><code>:compress</code> - This option can be used to indicate that compression should be used in the cache. This can be useful for transferring large cache entries over a slow network.</p></li>
<li><p><code>:compress_threshold</code> - This options is used in conjunction with the <code>:compress</code> option to indicate a threshold under which cache entries should not be compressed. This defaults to 16 kilobytes.</p></li>
<li><p><code>:expires_in</code> - This option sets an expiration time in seconds for the cache entry when it will be automatically removed from the cache.</p></li>
<li><p><code>:race_condition_ttl</code> - This option is used in conjunction with the <code>:expires_in</code> option. It will prevent race conditions when cache entries expire by preventing multiple processes from simultaneously regenerating the same entry (also known as the dog pile effect). This option sets the number of seconds that an expired entry can be reused while a new value is being regenerated. It's a good practice to set this value if you use the <code>:expires_in</code> option.</p></li>
</ul>
<h4 id="activesupport-cache-memorystore">2.3 ActiveSupport::Cache::MemoryStore</h4><p>This cache store keeps entries in memory in the same Ruby process. The cache store has a bounded size specified by the <code>:size</code> options to the initializer (default is 32Mb). When the cache exceeds the allotted size, a cleanup will occur and the least recently used entries will be removed.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.cache_store = :memory_store, { size: 64.megabytes }
</pre>
</div>
<p>If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then your Rails server process instances won't be able to share cache data with each other. This cache store is not appropriate for large application deployments, but can work well for small, low traffic sites with only a couple of server processes or for development and test environments.</p><h4 id="activesupport-cache-filestore">2.4 ActiveSupport::Cache::FileStore</h4><p>This cache store uses the file system to store entries. The path to the directory where the store files will be stored must be specified when initializing the cache.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.cache_store = :file_store, "/path/to/cache/directory"
</pre>
</div>
<p>With this cache store, multiple server processes on the same host can share a cache. Servers processes running on different hosts could share a cache by using a shared file system, but that set up would not be ideal and is not recommended. The cache store is appropriate for low to medium traffic sites that are served off one or two hosts.</p><p>Note that the cache will grow until the disk is full unless you periodically clear out old entries.</p><p>This is the default cache store implementation.</p><h4 id="activesupport-cache-memcachestore">2.5 ActiveSupport::Cache::MemCacheStore</h4><p>This cache store uses Danga's <code>memcached</code> server to provide a centralized cache for your application. Rails uses the bundled <code>dalli</code> gem by default. This is currently the most popular cache store for production websites. It can be used to provide a single, shared cache cluster with very high performance and redundancy.</p><p>When initializing the cache, you need to specify the addresses for all memcached servers in your cluster. If none is specified, it will assume memcached is running on the local host on the default port, but this is not an ideal set up for larger sites.</p><p>The <code>write</code> and <code>fetch</code> methods on this cache accept two additional options that take advantage of features specific to memcached. You can specify <code>:raw</code> to send a value directly to the server with no serialization. The value must be a string or number. You can use memcached direct operation like <code>increment</code> and <code>decrement</code> only on raw values. You can also specify <code>:unless_exist</code> if you don't want memcached to overwrite an existing entry.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com"
</pre>
</div>
<h4 id="activesupport-cache-ehcachestore">2.6 ActiveSupport::Cache::EhcacheStore</h4><p>If you are using JRuby you can use Terracotta's Ehcache as the cache store for your application. Ehcache is an open source Java cache that also offers an enterprise version with increased scalability, management, and commercial support. You must first install the jruby-ehcache-rails3 gem (version 1.1.0 or later) to use this cache store.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.cache_store = :ehcache_store
</pre>
</div>
<p>When initializing the cache, you may use the <code>:ehcache_config</code> option to specify the Ehcache config file to use (where the default is "ehcache.xml" in your Rails config directory), and the :cache_name option to provide a custom name for your cache (the default is rails_cache).</p><p>In addition to the standard <code>:expires_in</code> option, the <code>write</code> method on this cache can also accept the additional <code>:unless_exist</code> option, which will cause the cache store to use Ehcache's <code>putIfAbsent</code> method instead of <code>put</code>, and therefore will not overwrite an existing entry. Additionally, the <code>write</code> method supports all of the properties exposed by the <a href="http://ehcache.org/apidocs/net/sf/ehcache/Element.html">Ehcache Element class</a> , including:</p>
<table>
<thead>
<tr>
<th>Property</th>
<th>Argument Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>elementEvictionData</td>
<td>ElementEvictionData</td>
<td>Sets this element's eviction data instance.</td>
</tr>
<tr>
<td>eternal</td>
<td>boolean</td>
<td>Sets whether the element is eternal.</td>
</tr>
<tr>
<td>timeToIdle, tti</td>
<td>int</td>
<td>Sets time to idle</td>
</tr>
<tr>
<td>timeToLive, ttl, expires_in</td>
<td>int</td>
<td>Sets time to Live</td>
</tr>
<tr>
<td>version</td>
<td>long</td>
<td>Sets the version attribute of the ElementAttributes object.</td>
</tr>
</tbody>
</table>
<p>These options are passed to the <code>write</code> method as Hash options using either camelCase or underscore notation, as in the following examples:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Rails.cache.write('key', 'value', time_to_idle: 60.seconds, timeToLive: 600.seconds)
caches_action :index, expires_in: 60.seconds, unless_exist: true
</pre>
</div>
<p>For more information about Ehcache, see <a href="http://ehcache.org/">http://ehcache.org/</a> .
For more information about Ehcache for JRuby and Rails, see <a href="http://ehcache.org/documentation/jruby.html">http://ehcache.org/documentation/jruby.html</a></p><h4 id="activesupport-cache-nullstore">2.7 ActiveSupport::Cache::NullStore</h4><p>This cache store implementation is meant to be used only in development or test environments and it never stores anything. This can be very useful in development when you have code that interacts directly with <code>Rails.cache</code>, but caching may interfere with being able to see the results of code changes. With this cache store, all <code>fetch</code> and <code>read</code> operations will result in a miss.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.cache_store = :null_store
</pre>
</div>
<h4 id="custom-cache-stores">2.8 Custom Cache Stores</h4><p>You can create your own custom cache store by simply extending <code>ActiveSupport::Cache::Store</code> and implementing the appropriate methods. In this way, you can swap in any number of caching technologies into your Rails application.</p><p>To use a custom cache store, simple set the cache store to a new instance of the class.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.cache_store = MyCacheStore.new
</pre>
</div>
<h4 id="cache-keys">2.9 Cache Keys</h4><p>The keys used in a cache can be any object that responds to either <code>:cache_key</code> or to <code>:to_param</code>. You can implement the <code>:cache_key</code> method on your classes if you need to generate custom keys. Active Record will generate keys based on the class name and record id.</p><p>You can use Hashes and Arrays of values as cache keys.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# This is a legal cache key
Rails.cache.read(site: "mysite", owners: [owner_1, owner_2])
</pre>
</div>
<p>The keys you use on <code>Rails.cache</code> will not be the same as those actually used with the storage engine. They may be modified with a namespace or altered to fit technology backend constraints. This means, for instance, that you can't save values with <code>Rails.cache</code> and then try to pull them out with the <code>memcache-client</code> gem. However, you also don't need to worry about exceeding the memcached size limit or violating syntax rules.</p><h3 id="conditional-get-support">3 Conditional GET support</h3><p>Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn't changed since the last request and can be safely pulled from the browser cache.</p><p>They work by using the <code>HTTP_IF_NONE_MATCH</code> and <code>HTTP_IF_MODIFIED_SINCE</code> headers to pass back and forth both a unique content identifier and the timestamp of when the content was last changed. If the browser makes a request where the content identifier (etag) or last modified since timestamp matches the server's version then the server only needs to send back an empty response with a not modified status.</p><p>It is the server's (i.e. our) responsibility to look for a last modified timestamp and the if-none-match header and determine whether or not to send back the full response. With conditional-get support in Rails this is a pretty easy task:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ApplicationController
def show
@product = Product.find(params[:id])
# If the request is stale according to the given timestamp and etag value
# (i.e. it needs to be processed again) then execute this block
if stale?(last_modified: @product.updated_at.utc, etag: @product.cache_key)
respond_to do |wants|
# ... normal response processing
end
end
# If the request is fresh (i.e. it's not modified) then you don't need to do
# anything. The default render checks for this using the parameters
# used in the previous call to stale? and will automatically send a
# :not_modified. So that's it, you're done.
end
end
</pre>
</div>
<p>Instead of an options hash, you can also simply pass in a model, Rails will use the <code>updated_at</code> and <code>cache_key</code> methods for setting <code>last_modified</code> and <code>etag</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ApplicationController
def show
@product = Product.find(params[:id])
if stale?(@product)
respond_to do |wants|
# ... normal response processing
end
end
end
end
</pre>
</div>
<p>If you don't have any special response processing and are using the default rendering mechanism (i.e. you're not using respond_to or calling render yourself) then you've got an easy helper in fresh_when:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ApplicationController
# This will automatically send back a :not_modified if the request is fresh,
# and will render the default template (product.*) if it's stale.
def show
@product = Product.find(params[:id])
fresh_when last_modified: @product.published_at.utc, etag: @product
end
end
</pre>
</div>
<h3>反饋</h3>
<p>
歡迎幫忙改善指南的品質。
</p>
<p>
如發現任何錯誤之處,歡迎修正。開始貢獻前,可以先閱讀<a href="http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation">貢獻指南:文件</a>。
</p>
<p>翻譯如有錯誤,深感抱歉,歡迎 <a href="https://github.com/docrails-tw/guides/fork">Fork</a> 修正,或至此處<a href="https://github.com/docsrails-tw/guides/issues/new">回報</a>。</p>
<p>
文章可能有未完成或過時的內容。請先檢查 <a href="http://edgeguides.rubyonrails.org">Edge Guides</a> 來確定問題在 master 是否已經修掉了。再上 master 補上缺少的文件。內容參考 <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails 指南準則</a>來了解行文風格。
</p>
<p>最後,任何關於 Ruby on Rails 文件的討論,歡迎至 <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs 郵件論壇</a>。
</p>
</div>
</div>
</div>
<hr class="hide">
<div id="footer">
<div class="wrapper">
<p>本著作係採用<a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh_TW">創用 CC 姓名標示-相同方式分享 4.0 國際授權條款</a>授權。</p>
<p>“Rails”、“Ruby on Rails”,以及 Rails logo 為 David Heinemeier Hansson 的商標。版權所有。</p>
</div>
</div>
<script src="javascripts/jquery.min.js"></script>
<script src="javascripts/responsive-tables.js"></script>
<script src="javascripts/guides.js"></script>
<script src="javascripts/syntaxhighlighter/shCore.js"></script>
<script src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
<script src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
<script src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
<script src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
<script type="text/javascript">
SyntaxHighlighter.all();
$(guidesIndex.bind);
</script>
<script>
(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,"script","//www.google-analytics.com/analytics.js","ga");
ga("create", "UA-49903900-1", "auto");
ga("require", "displayfeatures");
ga("send", "pageview");
</script>
</body>
</html>