缓存cache(5.2新:redis): gem faker (6600✨) 命令行工具curl(系统内置,可在git上看到文档)

⚠️本章节记录缓存的一些方法的用法案例,配合这篇博客一起阅读:https://i.cnblogs.com/EditPosts.aspx?postid=8776632 

 

前置种子 

https://github.com/stympy/faker

如有个Company模型,含有一个name属性。弄出三十个实例变量:

30.times do
  company = Company.create(:name => Faker::Company.unique.name)
  if company.save
    SecureRandom.random_number(100).times do
      company.employees.create(
        first_name: Faker::Name.first_name,
        last_name: Faker::Name.last_name,
        phone_number: Faker::PhoneNumber.phone_number
      )
    end
  end
end

Faker::Company是内置的类。

 

unique方法让name的值都是唯一的。

 

SecureRandom是一个module,random_number(100)在100内生成随机整数。

 

 


 

HTTP Caching

目的:加快下载速度,如果已经从服务器下载了网页,并得知没有变化,那么就不从新下载网页

 

网页浏览器知道当它下载了一个resource(a web page),会把它放入它的cache。在第二次请求request,浏览器传递这个信息给服务器:If-Modified-Since: header 。服务器会把这个信息和相关文件比较,然后发送新版本或者返回一个HTTP 304 not Modified file 作为response. 

 


fresh_when方法 

 

在控制器中添加:

  def show
    fresh_when last_modified: @company.updated_at

    #也可以简写etag: @company 

  end

看log:显示:

第一次Completed 200 OK in 34ms (Views: 31.6ms | ActiveRecord: 0.5ms) 

再刷新:  304 Not Modified in 1ms (ActiveRecord: 0.1ms)

 


 

curl is a tool to transfer data from or to a server

 curl [option/url]

https://github.com/curl/curl 

 

$ curl -I http://localhost:3000/companies/1

option:

-I,仅仅显示头部。 

-i, -include  显示Include the HTTP response headers in the output

-v, 显示几乎全部信息,包括网页的html 。对debug有帮助.

 


 

当前用户:current_user and other potential parameters

 

ActionController::ConditionalGet::ClassMethods#etag

给etag增加指定的条件,当考虑是否更新时,看是否是当前用户的关联对象。

 

class ApplicationController < ActionController::Base
  etag {current_user.try :id}

  #在具体的控制器中,首行写上也可以。 

end
 

 

Stale?方法

 

和fresh_when的区别是可以指定respond_to的格式,如json. 

  def show
    # fresh_when last_modified: @company.updated_at
    if stale? @company
      respond_to do |format|
        format.html
        format.json {render json: @company}
      end
    end
  end

 


 

expires_in 方法

用于设置缓存过期的时间。expires_in(20.minutes)就是20分钟后过期。 

def show

 expires_in 2.minutes

  fresh_when @company, public: true

end 

 

$ curl -I <url>

HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Download-Options: noopen
X-Permitted-Cross-Domain-Policies: none
Referrer-Policy: strict-origin-when-cross-origin
Date: Sun, 10 Jun 2018 11:41:47 GMT
ETag: W/"404a3742ba49f816596aab7b1858d68c"
Last-Modified: Sun, 10 Jun 2018 10:03:29 GMT
Content-Type: text/html; charset=utf-8
Cache-Control: max-age=120, private  #这是设置120秒后过期。

 



 

fragment cache

 

使用碎片缓存可以单独缓存部分视图页面。碎片缓存和HTTP caching已经page caching是可以一起使用的。

 

$ rails dev:cache 

#⚠️在开发模块手动打开碎片缓存功能。而在产品模式,碎片缓存是默认使用的。

 

把整个表格都包含进去 cache('table_of_all_companies' )

<% cache('name_of_cache') do %>

  [...]

<% end %> 

 


 

Deleting the Fragment Cache

 

如果使用碎片缓存的话,在after_create, after_update, before_destroy上清除对应的缓存,使用AbstractController::caching::fragment  expire_fragment方法

class Employee < ActiveRecord::Base  ⚠️Company 模块也要➕上

  belongs_to :company, touch: true

  after_create   :expire_cache
  after_update   :expire_cache
  before_destroy :expire_cache

  def expire_cache

    ActionController::Base.new.expire_fragment('table_of_all_companies')

  end

end 

 

扩展:

ActionControllers是web请求的核心。它们由多个action组成,在request中执行并渲染一个模版或者redirects to 另外的action。

默认, ApplicationController继承自ActionController::Base。所有其他的controller继承它。 

所有的methods都由2个基本的模式: Get-and-show, do-and-redirect.

 

备注:我觉得无需使用这个。因为fresh_when中会判断是否发生变化。 的确,见下节👇。

 


 

自动化到期的缓存。

 

赋予一个碎片缓存唯一的名字,rails就会generate一个cache key给这个碎片。

 

使用cache_key(timestamp_column = :updated_at)生成一个cache key 由对象的id和updated_time组成,一旦update_time发生变化,cache key 就会变化。由是从新加载缓存。 

<% cache(@companies) do %> 则可以自动化到期碎片缓存了。

 

在config/environments/development.rb中,增加一行代码可以在log中显示cache key的名字。

config.action_controller.enable_fragment_cache_loggin = true

 


 

Russian Doll Caching

 

很管用。。主要用于数据库关联的嵌套表格table。

当一行发生变化时,只从新从服务器render改变的这一行,其他的行还是从缓存中读取。这会节省大量资源。本例,2层缓存,也叫俄罗斯套娃:

<% cache(@companies) do %>
  <table>
    <thead>

。。。略 

    </thead>
    <tbody>
      <% @companies.each do |company| %>
        <% cache(company) do%>
          <tr>
            <td><%= @count %></td>
    。。。略
          </tr>
        <% end %>
      <% end %>
    </tbody>
  </table>
<% end %>

 

如果在log中显示fragment cache。会有write fragemnt和read fragment字样。 

 

 


Cache Store 

 

用来管理储存的碎片缓存。无需配置。每一个rails程序process都有单独的cache store。所以如果有多个rails processes并行运行在production system中,每个process都有自己的MemoryStore。不方便管理。

 


 

MemCacheStore 

流行的缓存存储器。配置:

 

config/environments/production.rb.:

config.cache_store = :mem_cache_store 


 

Redis: 5.2新增缓存存储器。见博客⬇️

https://www.cnblogs.com/chentianwei/p/8776632.html

 

 



 

Page Caching (停止)

已经被Rails4移除,但可以作为gem使用。作者说仍然很有力量。powerful。

⚠️: 需要配置服务器的额外知识。作者说网页缓存不适合弱心脏。 

 

在操作到caching the company index and show view这一步,没有增加public/deploy/companies/1.html。猜测是否没有配置web server。暂停学习。 


 


posted @ 2018-06-10 17:45  Mr-chen  阅读(190)  评论(0编辑  收藏  举报