分析Cache 在 Ruby China 里面的應用情況
首先給大家看一下 NewRelic 的報表
最近 24h 的平均響應時間

流量高的那些頁面 (Action)

訪問量搞的幾個 Action 的情況:
TopicsController#show

UsersController#show (比較慘,主要是 GitHub API 請求拖慢)

PS: 在發(fā)布這篇文章之前我有稍加修改了一下,GitHub 請求放到后臺隊列處理,新的結果是這樣:

TopicsController#index

HomeController#index

從上面的報表來看,目前 Ruby China 后端的請求,排除用戶主頁之外,響應時間都在 100ms 以內,甚至更低。
我們是如何做到的?
Markdown 緩存
Fragment Cache
數(shù)據緩存
ETag
靜態(tài)資源緩存 (JS,CSS,圖片)
Markdown 緩存
在內容修改的時候就算好 Markdown 的結果,存到數(shù)據庫,避免瀏覽的時候反復計算。
此外這個東西也特意不放到 Cache,而是放到數(shù)據庫里面:
為了持久化,避免 Memcached 停掉的時候,大量丟失;
避免過多占用緩存內存;
class Topic field :body # 存放原始內容,用于修改 field :body_html # 存放計算好的結果,用于顯示 before_save :markdown_body def markdown_body self.body_html = MarkdownTopicConverter.format(self.body) if self.body_changed? end end Fragment Cache
這個是 Ruby China 里面用得最多的緩存方案,也是速度提升的原因所在。
app/views/topics/_topic.html.erb
<% cache([topic, suggest]) do %>
<div class="topic topic_line topic_<%= topic.id %>">
<%= link_to(topic.replies_count,"#{topic_path(topic)}#reply#{topic.replies_count}",
:class => "count state_false") %>
... 省略內容部分
</div>
<% end %>
用 topic 的 cache_key 作為緩存 cache views/topics/{編號}-#{更新時間}/{suggest 參數(shù)}/{文件內容 MD5} -> views/topics/19105-20140508153844/false/bc178d556ecaee49971b0e80b3566f12
某些涉及到根據用戶帳號,有不同狀態(tài)顯示的地方,直接把完整 HTML 準備好,通過 JS 控制狀態(tài),比如目前的“喜歡“功能。
<script type="text/javascript">
var readed_topic_ids = <%= current_user.filter_readed_topics(@topics) %>;
for (var i = 0; i < readed_topic_ids.length; i++) {
topic_id = readed_topic_ids[i];
$(".topic_"+ topic_id + " .right_info .count").addClass("state_true");
}
</script>
再比如
app/views/topics/_reply.html.erb
<% cache([reply,"raw:#{@show_raw}"]) do %>
<div class="reply">
<div class="pull-left face"><%= user_avatar_tag(reply.user, :normal) %></div>
<div class="infos">
<div class="info">
<span class="name">
<%= user_name_tag(reply.user) %>
</span>
<span class="opts">
<%= likeable_tag(reply, :cache => true) %>
<%= link_to("", edit_topic_reply_path(@topic,reply), :class => "edit icon small_edit", 'data-uid' => reply.user_id, :title => "修改回帖")%>
<%= link_to("", "#", 'data-floor' => floor, 'data-login' => reply.user_login,
:title => t("topics.reply_this_floor"), :class => "icon small_reply" )
%>
</span>
</div>
<div class="body">
<%= sanitize_reply reply.body_html %>
</div>
</div>
</div>
<% end %>
同樣也是通過 reply 的 cache_key 來緩存 views/replies/202695-20140508081517/raw:false/d91dddbcb269f3e0172bf5d0d27e9088
同時這里還有復雜的用戶權限控制,用 JS 實現(xiàn);
<script type="text/javascript">
$(document).ready(function(){
<% if admin? %>
$("#replies .reply a.edit").css('display','inline-block');
<% elsif current_user %>
$("#replies .reply a.edit[data-uid='<%= current_user.id %>']").css('display','inline-block');
<% end %>
<% if current_user && !@user_liked_reply_ids.blank? %>
Topics.checkRepliesLikeStatus([<%= @user_liked_reply_ids.join(",") %>]);
<% end %>
})
</script>
數(shù)據緩存
其實 Ruby China 的大多數(shù) Model 查詢都沒有上 Cache 的,因為據實際狀況來看, MongoDB 的查詢響應時間都是很快的,大部分場景都是在 5ms 以內,甚至更低。
我們會做一些比價負責的數(shù)據查詢緩存,比如:GitHub Repos 獲取
def github_repos(user_id)
cache_key = "user:#{user_id}:github_repos"
items = Rails.cache.read(cache_key)
if items.blank?
items = real_fetch_from_github()
Rails.cache.write(cache_key, items, expires_in: 15.days)
end
return items
end
ETag
ETag 是在 HTTP Request, Response 可以帶上的一個參數(shù),用于檢測內容是否有更新過,以減少網絡開銷。
過程大概是這樣

Rails 的 fresh_when 方法可以幫助將你的查詢內容生成 ETag 信息
def show @topic = Topic.find(params[:id]) fresh_when(etag: [@topic]) end
靜態(tài)資源緩存
請不要小看這個東西,后端寫得再快,也有可能被這些拖慢(瀏覽器上面的表現(xiàn))!
1、合理利用 Rails Assets Pipeline,一定要開啟!
# config/environments/production.rb config.assets.digest = true
2、在 Nginx 里面將 CSS, JS, Image 的緩存有效期設成 max;
location ~ (/assets|/favicon.ico|/*.txt) {
access_log off;
expires max;
gzip_static on;
}
3、盡可能的減少一個頁面 JS, CSS, Image 的數(shù)量,簡單的方法是合并它們,減少 HTTP 請求開銷;
<head> ... 只有兩個 <link rel="stylesheet" /> <script src="http://ruby-china-files.b0.upaiyun.com/assets/app-24d4280cc6fda926e73419c126c71206.js"></script> ... </head>
一些 Tips
看統(tǒng)計日志,優(yōu)先處理流量高的頁面;
updated_at 是一個非常有利于幫助你清理緩存的東西,善用它!修改數(shù)據的時候別忽略它!
多關注你的 Rails Log 里面的查詢時間,100ms 一下的頁面響應時間是一個比較好的狀態(tài),超過 200ms 用戶就會感覺到遲鈍了。
相關文章
使用Ruby on Rails快速開發(fā)web應用的教程實例
這篇文章主要介紹了使用Ruby on Rails快速開發(fā)web應用的教程實例,本文來自于IBM官方技術文檔,需要的朋友可以參考下2015-04-04

