SlideShare uma empresa Scribd logo
1 de 35
Baixar para ler offline
Caching	
  With	
  Rails	
  
By	
  Carmen	
  Diaz	
  Echauri	
  –	
  cdechauri@gmail.com	
  
For	
  www.blazingcloud.net	
  
Rails	
  version	
  2.3.8	
  
Caching	
  with	
  Rails	
  
Scaling	
  your	
  ApplicaFons	
  
•  Rails	
  provides	
  by	
  default	
  three	
  techniques:	
  
– 	
  Page	
  Caching	
  	
  
– 	
  AcFon	
  Caching	
  
– Fragment	
  Caching	
  
Page	
  Caching	
  
•  Allows	
  the	
  request	
  for	
  a	
  generated	
  page	
  to	
  be	
  
fulfilled	
  by	
  the	
  webserver,	
  without	
  ever	
  having	
  
to	
  go	
  through	
  your	
  Rails	
  applicaFon.	
  
Client	
   Apache	
   Mongrel	
  
Public/users.html	
  
hOp://localhost:3000/users	
  
Page	
  Caching	
  
	
  Next	
  Fme	
  we	
  request	
  the	
  same	
  page,	
  apache	
  
will	
  load	
  the	
  page	
  from	
  the	
  filesystem	
  and	
  
send	
  it	
  back	
  to	
  the	
  client.	
  
Client	
   Apache	
   Mongrel	
  
Public/users.html	
  hOp://localhost:3000/users	
  
When	
  we	
  might	
  want	
  to	
  page	
  cached?	
  
•  When	
  every	
  user	
  always	
  sees	
  exactly	
  the	
  same	
  
content	
  on	
  a	
  page,	
  even	
  if	
  they	
  are	
  login	
  to	
  the	
  
admin	
  interface	
  or	
  not.	
  But	
  It's	
  always	
  the	
  
same.	
  
•  It	
  doesn't	
  change	
  so	
  oWen.	
  Maybe	
  once	
  per	
  
day,	
  week	
  or	
  month.	
  
Get	
  started	
  with	
  caching….	
  
•  Make	
  sure	
  
config.acFon_controller.perform_caching	
  is	
  
set	
  to	
  true	
  for	
  your	
  environment.	
  (config/
environments/development.rb)	
  
config.acFon_controller.perform_caching	
  =	
  true	
  
Page	
  Caching	
  
Page	
  Caching	
  OpFons	
  
•  format.json	
  {render	
  :json	
  =>	
  @users}	
  
•  format.iphone	
  
–  /config/iniFalizers/mime_types.rb	
  
•  Mime::Type.register_alias	
  “text/html”,	
  :iphone	
  
–  /app/views/users/index.iphone.erb	
  
/public/users.html	
  
/public/users.xml	
  
/public/users.json	
  
/public/users.iphone	
  
Caching	
  locaFon	
  
/config/environment.rb	
  
versus	
  
Page	
  caching	
  
•  Page	
  caching	
  ignores	
  all	
  parameters	
  
– hOp://localhost:3000/users?page=1	
  
Will	
  be	
  wriOen	
  out	
  	
  
so	
  if	
  someone	
  request	
  
hOp://localhost:3000/users?page=3	
  it	
  will	
  be	
  gegng	
  
users.html.	
  
AcFon	
  Caching	
  
•  Caching	
  stored	
  	
  
– Page	
  Caching	
  
•  Stored	
  on	
  Disk	
  
– AcFon	
  &	
  Fragment	
  Caching	
  
•  Use	
  the	
  configured	
  cache	
  that	
  we	
  configure	
  in	
  our	
  rails	
  
instance.	
  	
  
When	
  to	
  do	
  AcFon	
  Caching? 	
  	
  
•  When	
  we	
  need	
  filters	
  to	
  run	
  
– Like	
  authenFcaFon	
  	
  
Client	
   Apache	
   Mongrel	
  
Public/posts.html	
  
hOp://localhost:3000/posts	
  
Run	
  Filters	
  
(authenFcate)	
  
AcFon	
  Caching	
  
AcFon	
  Caching	
  
Didn’t	
  call	
  the	
  acFon.	
  It	
  loaded	
  straight	
  out	
  of	
  the	
  cache	
  
It	
  executed	
  the	
  acFon	
  
AcFon	
  Caching	
  OpFons	
  
/config/environments/development.rb	
  
•  config.cache_store	
  =	
  :file_store,	
  'tmp/cache’	
  
	
  	
  (AcFveSupport::Cache::FileStore)	
  	
  
•  config.cache_store	
  =	
  :memory_store	
  
	
  (AcFveSupport::Cache::MemoryStore)	
  	
  
–  {}	
  in	
  memory	
  –background-­‐.	
  But	
  you	
  can	
  run	
  out	
  of	
  memory	
  
–  No	
  sharing	
  between	
  processes.	
  You	
  cannot	
  use	
  it	
  if	
  you	
  run	
  more	
  than	
  
one	
  instance	
  of	
  your	
  rails	
  apps.	
  	
  
AcFon	
  Caching	
  OpFons….	
  
•  config.cache_store	
  =	
  :mem_cache_store	
  
•  config.cache_store	
  =	
  :mem_cache_store,	
  :namespace	
  =>	
  
“store”	
  	
  (share	
  apps)	
  
•  config.cache_store	
  =	
  :mem_cache_store,	
  192.168.1.255:1001,	
  
192.168.1.255:1002	
  (mulFple	
  servers)	
  
	
  (AcFveSupport::Cache::MemCacheStore)	
  	
  
•  config.cache_store	
  =	
  :drb_store	
  
(AcFveSupport::Cache::DRbStore)	
  	
  
•  config.cache_store	
  =	
  :custom_store	
  
AcFon	
  Caching	
  	
  
•  Features	
  
–  Cached	
  the	
  acFon	
  without	
  the	
  layout.	
  
it	
  will	
  only	
  cache	
  your	
  acFon	
  content.	
  
So,	
  if	
  you	
  need	
  some	
  sort	
  of	
  data	
  you	
  might	
  want	
  to	
  use	
  
before_filter	
  and	
  set	
  you	
  instance	
  variable	
  	
  	
  
AcFon	
  Caching	
  	
  
•  Features	
  (cont)	
  
•  CondiFonal	
  AcFon	
  acFon	
  using	
  :if	
  (or	
  :unless)	
  =>	
  Proc.new{….}	
  to	
  
specify	
  when	
  the	
  acFon	
  should	
  be	
  cached.	
  	
  
•  Specific	
  path	
  using	
  :cache_path	
  =>	
  Proc.new	
  {	
  |controller|	
  or	
  
:cache_path	
  =>	
  <method>	
  
:expires_in	
  =>1.hour	
  to	
  specify	
  when	
  the	
  acFon	
  should	
  be	
  cached.	
  	
  	
  
(only	
  with	
  memcached	
  &	
  rails	
  >	
  2.1)	
  
Fragment	
  Caching	
  
•  Is	
  useful	
  for	
  dynamic	
  web	
  applicaFons	
  
•  Allows	
  you	
  to	
  fragment	
  many	
  pieces	
  of	
  the	
  view.	
  
The	
  pieces	
  will	
  be	
  wrapped	
  in	
  a	
  cache	
  block	
  and	
  
served	
  out	
  of	
  the	
  cache	
  store	
  when	
  the	
  next	
  
request	
  comes	
  in.	
  	
  
Client	
   Apache	
   Mongrel	
  
header	
  
hOp://localhost:3000/users	
  
body	
  
widgets	
  
Fragment	
  Caching	
  
	
  To	
  implement	
  fragment	
  caching,	
  you	
  cache	
  your	
  method	
  	
  in	
  
the	
  view.	
  
All	
  keys	
  are	
  prefixed	
  with	
  "views/"	
  
Fragment	
  Caching	
  
You	
  can	
  create	
  your	
  own	
  key:	
  <%	
  cache("#{@user.id}-­‐recents_joined")	
  do	
  %>	
  or	
  
use	
  the	
  rails	
  way	
  	
  
<%	
  cache([user,	
  post,	
  “toolbar”])	
  do	
  %>	
  
Memcached	
  
•  Is	
  a	
  hash	
  in	
  memory,	
  	
  key-­‐value	
  store	
  	
  {}	
  in	
  memory	
  
(LiveJournal)	
  	
  
–  To	
  implement	
  /config/environments/producFon.rb	
  
config.cache_store	
  =	
  :mem_cache_store	
  
Same	
  thing	
  as	
  config.cache_store	
  =	
  :memory_store	
  	
  
but	
  it	
  runs	
  as	
  a	
  separate	
  process.	
  You	
  can	
  have	
  several	
  rails	
  
instances	
  that	
  references	
  the	
  same	
  mencached	
  instance	
  	
  
-­‐	
  Note:	
  make	
  sure	
  to	
  install	
  the	
  gem	
  memcached-­‐client.	
  
Memcached	
  uses	
  	
  
•  Fragment	
  Cache	
  Store	
  
•  AcFon	
  &	
  Fragment	
  Caching	
  
Memcached	
  uses	
  	
  
•  As	
  an	
  Object	
  Store	
  
–  Rails.cache.read	
  
–  Rails.cache.write	
  
–  Rails.cache.fetch	
  
–  Rails.cache.delete	
  
–  Rails.cache.exists?	
  
–  Rails.cache.clear	
  
–  Rails.cache.increment	
  
–  Rails.cache.clear	
  
Memcached	
  uses	
  	
  
Memcached	
  ….	
  Some	
  points:	
  
-­‐	
  Expire	
  at	
  
def	
  self.recent	
  
	
  	
  Rails.cache.fetch("recent_posts",	
  :expires_in	
  =>	
  30.minutes)	
  do	
  
	
   	
  	
   	
  self.find(:all,	
  :limit	
  =>	
  10)	
  
	
  end	
  
end	
  
Run	
  this	
  query	
  every	
  30	
  minutes…	
  	
  
-­‐	
   	
  You	
  don’t	
  need	
  to	
  have	
  memcached	
  installed	
  to	
  develop	
  locally	
  
	
  You	
  will	
  get	
  MemCacheError	
  (No	
  connecFon	
  to	
  server):	
  No	
  
connecFon	
  to	
  server	
  Cache	
  miss:	
  
	
  But,	
  your	
  app	
  will	
  work	
  just	
  fine.	
  Rails	
  will	
  always	
  execute	
  the	
  
contents	
  of	
  the	
  fetch	
  blocks,	
  and	
  will	
  return	
  nil	
  for	
  any	
  reads.	
  
Expiring	
  cached	
  pages	
  
One’s	
  first	
  inclinaFon	
  may	
  be	
  to	
  expire	
  pages	
  in	
  the	
  Controller	
  and	
  usually	
  via	
  the	
  
update	
  method.	
  	
  
Depending	
  on	
  which	
  technique	
  you	
  choose	
  to	
  expire	
  pages	
  you	
  can	
  use	
  the	
  method	
  
expire_page	
  {acFon,fragment}	
  
Instead	
  of	
  having	
  expire	
  methods	
  around	
  your	
  controllers,	
  to	
  clear	
  cache	
  files	
  based	
  
on	
  when	
  a	
  model	
  is	
  updated,	
  sweepers	
  are	
  the	
  way	
  to	
  go.	
  
Expiring	
  cached	
  page	
  
AcFonController::Caching::Sweeper	
  class.	
  (Share	
  Objects)	
  	
  
–  Can	
  observe	
  Controllers	
  
–  Can	
  observe	
  Models	
  
Hooks:	
  
Any	
  observer	
  callbacks	
  
	
  aWer	
  create	
  
	
  aWer	
  destroy	
  
	
  aWer_save,	
  etc.	
  
Also	
  in	
  any	
  controllers	
  callbacks	
  
•  before/aWer_<controller_name>	
  
•  before/aWer_<controller_name>_<acFon>	
  
Expiring	
  cached	
  page	
  
To	
  implement	
  sweepers:	
  
	
  Declare	
  a	
  new	
  load	
  path	
  in	
  /config/environment.rb	
  to	
  keep	
  the	
  sweepers	
  
separate	
  from	
  models	
  and	
  controllers.	
  
config.load_paths	
  <<	
  "#{RAILS_ROOT}/app/sweepers”	
  
Create	
  the	
  folder	
  and	
  the	
  observer	
  files	
  
Expiring	
  cached	
  page	
  
And	
  then	
  we	
  will	
  tell	
  the	
  controller	
  to	
  use	
  the	
  sweeper	
  
cache_sweeper	
  :user_sweeper,	
  :only	
  =>	
  [:create,	
  :update,	
  :destroy]	
  
When	
  to	
  call	
  the	
  method	
  
Observe	
  the	
  model	
  
Expiring	
  cached	
  page	
  
Another	
  way	
  to	
  expire.	
  
Clearing	
  the	
  cache	
  
And	
  you	
  could	
  use	
  it	
  in	
  a	
  cron	
  call…	
  
Some	
  thoughts	
  
	
  ImplemenFng	
  page	
  caching	
  can	
  be	
  easy.	
  However,	
  expiring	
  can	
  be	
  
prove	
  to	
  be	
  a	
  bit	
  more	
  challenging	
  .	
  
•  I	
  find	
  tesFng	
  kind	
  of	
  tricky.	
  
•  I	
  read	
  through	
  numerous	
  blog	
  posts	
  but	
  	
  I	
  couldn’t	
  	
  quite	
  figure	
  out	
  
how	
  to	
  get	
  things	
  to	
  work	
  as	
  I	
  hoped.	
  	
  
•  The	
  following	
  are	
  alternaFves	
  I’ve	
  recently	
  used:	
  	
  
–  Custom	
  Macthers	
  by	
  overwriFng	
  the	
  matches?	
  method	
  
•  AcFonController::Caching::AcFons	
  	
  
–  	
  Build	
  your	
  CachePage	
  /	
  Fragment	
  Page	
  class	
  and	
  use	
  	
  
•  AcFonController::Base.expire_page(	
  	
  )	
  
•  AcFonController::Caching::Fragments	
  
–  expire_fragment	
  
–  fragment_cache_key	
  
–  fragment_exist?	
  
–  read_fragment	
  
–  write_fragment	
  
Caching/Expiring in Rails

Mais conteúdo relacionado

Mais procurados

Ansible automation tool with modules
Ansible automation tool with modulesAnsible automation tool with modules
Ansible automation tool with modulesmohamedmoharam
 
EC2 AMI Factory with Chef, Berkshelf, and Packer
EC2 AMI Factory with Chef, Berkshelf, and PackerEC2 AMI Factory with Chef, Berkshelf, and Packer
EC2 AMI Factory with Chef, Berkshelf, and PackerGeorge Miranda
 
Ansible at work
Ansible at workAnsible at work
Ansible at workBas Meijer
 
Infrastructureascode slideshare-160331143725
Infrastructureascode slideshare-160331143725Infrastructureascode slideshare-160331143725
Infrastructureascode slideshare-160331143725miguel dominguez
 
Host Health Monitoring with Docker Run
Host Health Monitoring with Docker RunHost Health Monitoring with Docker Run
Host Health Monitoring with Docker RunNoah Zoschke
 
Debugging webOS applications
Debugging webOS applicationsDebugging webOS applications
Debugging webOS applicationsfpatton
 
Puppet Camp DC 2014: Managing Puppet with MCollective
Puppet Camp DC 2014: Managing Puppet with MCollectivePuppet Camp DC 2014: Managing Puppet with MCollective
Puppet Camp DC 2014: Managing Puppet with MCollectivePuppet
 
IaC and Immutable Infrastructure with Terraform, Сергей Марченко
IaC and Immutable Infrastructure with Terraform, Сергей МарченкоIaC and Immutable Infrastructure with Terraform, Сергей Марченко
IaC and Immutable Infrastructure with Terraform, Сергей МарченкоSigma Software
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Racksickill
 
The secret life of a dispatcher (Adobe CQ AEM)
The secret life of a dispatcher (Adobe CQ AEM)The secret life of a dispatcher (Adobe CQ AEM)
The secret life of a dispatcher (Adobe CQ AEM)Venugopal Gummadala
 
Tomcat configuration
Tomcat configurationTomcat configuration
Tomcat configurationDima Gomaa
 
Create dynamic sites with PHP & MySQL
Create dynamic sites with PHP & MySQLCreate dynamic sites with PHP & MySQL
Create dynamic sites with PHP & MySQLkangaro10a
 
Vagrant for real codemotion (moar tips! ;-))
Vagrant for real codemotion (moar tips! ;-))Vagrant for real codemotion (moar tips! ;-))
Vagrant for real codemotion (moar tips! ;-))Michele Orselli
 
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Campmodern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet CampPuppet
 

Mais procurados (19)

Rails Security
Rails SecurityRails Security
Rails Security
 
Ansible automation tool with modules
Ansible automation tool with modulesAnsible automation tool with modules
Ansible automation tool with modules
 
EC2 AMI Factory with Chef, Berkshelf, and Packer
EC2 AMI Factory with Chef, Berkshelf, and PackerEC2 AMI Factory with Chef, Berkshelf, and Packer
EC2 AMI Factory with Chef, Berkshelf, and Packer
 
Ansible at work
Ansible at workAnsible at work
Ansible at work
 
Intro to Rack
Intro to RackIntro to Rack
Intro to Rack
 
Infrastructureascode slideshare-160331143725
Infrastructureascode slideshare-160331143725Infrastructureascode slideshare-160331143725
Infrastructureascode slideshare-160331143725
 
Host Health Monitoring with Docker Run
Host Health Monitoring with Docker RunHost Health Monitoring with Docker Run
Host Health Monitoring with Docker Run
 
Debugging webOS applications
Debugging webOS applicationsDebugging webOS applications
Debugging webOS applications
 
Puppet Camp DC 2014: Managing Puppet with MCollective
Puppet Camp DC 2014: Managing Puppet with MCollectivePuppet Camp DC 2014: Managing Puppet with MCollective
Puppet Camp DC 2014: Managing Puppet with MCollective
 
IaC and Immutable Infrastructure with Terraform, Сергей Марченко
IaC and Immutable Infrastructure with Terraform, Сергей МарченкоIaC and Immutable Infrastructure with Terraform, Сергей Марченко
IaC and Immutable Infrastructure with Terraform, Сергей Марченко
 
Sinatra for REST services
Sinatra for REST servicesSinatra for REST services
Sinatra for REST services
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Ansible - A 'crowd' introduction
Ansible - A 'crowd' introductionAnsible - A 'crowd' introduction
Ansible - A 'crowd' introduction
 
The secret life of a dispatcher (Adobe CQ AEM)
The secret life of a dispatcher (Adobe CQ AEM)The secret life of a dispatcher (Adobe CQ AEM)
The secret life of a dispatcher (Adobe CQ AEM)
 
Tomcat configuration
Tomcat configurationTomcat configuration
Tomcat configuration
 
Create dynamic sites with PHP & MySQL
Create dynamic sites with PHP & MySQLCreate dynamic sites with PHP & MySQL
Create dynamic sites with PHP & MySQL
 
Vagrant for real codemotion (moar tips! ;-))
Vagrant for real codemotion (moar tips! ;-))Vagrant for real codemotion (moar tips! ;-))
Vagrant for real codemotion (moar tips! ;-))
 
Deployment automation
Deployment automationDeployment automation
Deployment automation
 
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Campmodern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
 

Destaque

Asuncion intro a las tic- macarena torres
Asuncion intro a las tic- macarena torresAsuncion intro a las tic- macarena torres
Asuncion intro a las tic- macarena torresMaca Torres
 
Asuncion del Paraguay Capital de mis amores
Asuncion del Paraguay Capital de mis amoresAsuncion del Paraguay Capital de mis amores
Asuncion del Paraguay Capital de mis amoresJorge Mantilla
 
My journey through Rspec
My journey through RspecMy journey through Rspec
My journey through Rspeccdechauri
 
Marchando sobre Rieles
Marchando sobre RielesMarchando sobre Rieles
Marchando sobre Rielescdechauri
 
Linguas oficiais de Europa
Linguas oficiais de EuropaLinguas oficiais de Europa
Linguas oficiais de EuropaLoli Cid Cid
 
Meetup training Taller RoR
Meetup training Taller RoR Meetup training Taller RoR
Meetup training Taller RoR cdechauri
 
Cazal jorge.ppt
Cazal jorge.pptCazal jorge.ppt
Cazal jorge.pptcazaljd
 
SEO: Getting Personal
SEO: Getting PersonalSEO: Getting Personal
SEO: Getting PersonalKirsty Hulse
 

Destaque (9)

Asuncion intro a las tic- macarena torres
Asuncion intro a las tic- macarena torresAsuncion intro a las tic- macarena torres
Asuncion intro a las tic- macarena torres
 
Madre de ciudades cba11
Madre de ciudades cba11Madre de ciudades cba11
Madre de ciudades cba11
 
Asuncion del Paraguay Capital de mis amores
Asuncion del Paraguay Capital de mis amoresAsuncion del Paraguay Capital de mis amores
Asuncion del Paraguay Capital de mis amores
 
My journey through Rspec
My journey through RspecMy journey through Rspec
My journey through Rspec
 
Marchando sobre Rieles
Marchando sobre RielesMarchando sobre Rieles
Marchando sobre Rieles
 
Linguas oficiais de Europa
Linguas oficiais de EuropaLinguas oficiais de Europa
Linguas oficiais de Europa
 
Meetup training Taller RoR
Meetup training Taller RoR Meetup training Taller RoR
Meetup training Taller RoR
 
Cazal jorge.ppt
Cazal jorge.pptCazal jorge.ppt
Cazal jorge.ppt
 
SEO: Getting Personal
SEO: Getting PersonalSEO: Getting Personal
SEO: Getting Personal
 

Semelhante a Caching/Expiring in Rails

Four Ways to Improve ASP .NET Performance and Scalability
 Four Ways to Improve ASP .NET Performance and Scalability Four Ways to Improve ASP .NET Performance and Scalability
Four Ways to Improve ASP .NET Performance and ScalabilityAlachisoft
 
Drupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case StudyDrupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case Studyhernanibf
 
cache concepts and varnish-cache
cache concepts and varnish-cachecache concepts and varnish-cache
cache concepts and varnish-cacheMarc Cortinas Val
 
Setting up your Multi Engine Environment - Apache Railo and ColdFusion
Setting up your Multi Engine Environment - Apache Railo and ColdFusionSetting up your Multi Engine Environment - Apache Railo and ColdFusion
Setting up your Multi Engine Environment - Apache Railo and ColdFusionGavin Pickin
 
Http caching 101 and a bit of CacheCow
Http caching 101 and a bit of CacheCowHttp caching 101 and a bit of CacheCow
Http caching 101 and a bit of CacheCowAli Kheyrollahi
 
Advanced caching techniques with ehcache, big memory, terracotta, and coldfusion
Advanced caching techniques with ehcache, big memory, terracotta, and coldfusionAdvanced caching techniques with ehcache, big memory, terracotta, and coldfusion
Advanced caching techniques with ehcache, big memory, terracotta, and coldfusionColdFusionConference
 
Html5 cache mechanism & local storage
Html5 cache mechanism & local storageHtml5 cache mechanism & local storage
Html5 cache mechanism & local storageSendhil Kumar Kannan
 
Rails Caching: Secrets From the Edge
Rails Caching: Secrets From the EdgeRails Caching: Secrets From the Edge
Rails Caching: Secrets From the EdgeFastly
 
Rails Caching Secrets from the Edge
Rails Caching Secrets from the EdgeRails Caching Secrets from the Edge
Rails Caching Secrets from the EdgeMichael May
 
Caching with Memcached and APC
Caching with Memcached and APCCaching with Memcached and APC
Caching with Memcached and APCBen Ramsey
 
T3DD12 Caching with Varnish
T3DD12 Caching with VarnishT3DD12 Caching with Varnish
T3DD12 Caching with VarnishAOE
 
T3DD12 Caching with Varnish
T3DD12 Caching with VarnishT3DD12 Caching with Varnish
T3DD12 Caching with VarnishAOE
 
My Opera meets Varnish, Dec 2009
My Opera meets Varnish, Dec 2009My Opera meets Varnish, Dec 2009
My Opera meets Varnish, Dec 2009Cosimo Streppone
 
Developing High Performance and Scalable ColdFusion Application Using Terraco...
Developing High Performance and Scalable ColdFusion Application Using Terraco...Developing High Performance and Scalable ColdFusion Application Using Terraco...
Developing High Performance and Scalable ColdFusion Application Using Terraco...ColdFusionConference
 

Semelhante a Caching/Expiring in Rails (20)

Rails caching
Rails cachingRails caching
Rails caching
 
Four Ways to Improve ASP .NET Performance and Scalability
 Four Ways to Improve ASP .NET Performance and Scalability Four Ways to Improve ASP .NET Performance and Scalability
Four Ways to Improve ASP .NET Performance and Scalability
 
Caching By Nyros Developer
Caching By Nyros DeveloperCaching By Nyros Developer
Caching By Nyros Developer
 
Ror caching
Ror cachingRor caching
Ror caching
 
Drupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case StudyDrupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case Study
 
cache concepts and varnish-cache
cache concepts and varnish-cachecache concepts and varnish-cache
cache concepts and varnish-cache
 
Setting up your Multi Engine Environment - Apache Railo and ColdFusion
Setting up your Multi Engine Environment - Apache Railo and ColdFusionSetting up your Multi Engine Environment - Apache Railo and ColdFusion
Setting up your Multi Engine Environment - Apache Railo and ColdFusion
 
Http caching 101 and a bit of CacheCow
Http caching 101 and a bit of CacheCowHttp caching 101 and a bit of CacheCow
Http caching 101 and a bit of CacheCow
 
Varnish –Http Accelerator
Varnish –Http AcceleratorVarnish –Http Accelerator
Varnish –Http Accelerator
 
Advanced caching techniques with ehcache, big memory, terracotta, and coldfusion
Advanced caching techniques with ehcache, big memory, terracotta, and coldfusionAdvanced caching techniques with ehcache, big memory, terracotta, and coldfusion
Advanced caching techniques with ehcache, big memory, terracotta, and coldfusion
 
Html5 cache mechanism & local storage
Html5 cache mechanism & local storageHtml5 cache mechanism & local storage
Html5 cache mechanism & local storage
 
Rails Caching: Secrets From the Edge
Rails Caching: Secrets From the EdgeRails Caching: Secrets From the Edge
Rails Caching: Secrets From the Edge
 
Rails Caching Secrets from the Edge
Rails Caching Secrets from the EdgeRails Caching Secrets from the Edge
Rails Caching Secrets from the Edge
 
Cache is King
Cache is KingCache is King
Cache is King
 
Caching with Memcached and APC
Caching with Memcached and APCCaching with Memcached and APC
Caching with Memcached and APC
 
T3DD12 Caching with Varnish
T3DD12 Caching with VarnishT3DD12 Caching with Varnish
T3DD12 Caching with Varnish
 
T3DD12 Caching with Varnish
T3DD12 Caching with VarnishT3DD12 Caching with Varnish
T3DD12 Caching with Varnish
 
catching in c#.pptx
catching in c#.pptxcatching in c#.pptx
catching in c#.pptx
 
My Opera meets Varnish, Dec 2009
My Opera meets Varnish, Dec 2009My Opera meets Varnish, Dec 2009
My Opera meets Varnish, Dec 2009
 
Developing High Performance and Scalable ColdFusion Application Using Terraco...
Developing High Performance and Scalable ColdFusion Application Using Terraco...Developing High Performance and Scalable ColdFusion Application Using Terraco...
Developing High Performance and Scalable ColdFusion Application Using Terraco...
 

Último

(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 

Último (20)

(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 

Caching/Expiring in Rails

  • 1. Caching  With  Rails   By  Carmen  Diaz  Echauri  –  cdechauri@gmail.com   For  www.blazingcloud.net   Rails  version  2.3.8  
  • 2. Caching  with  Rails   Scaling  your  ApplicaFons   •  Rails  provides  by  default  three  techniques:   –   Page  Caching     –   AcFon  Caching   – Fragment  Caching  
  • 3. Page  Caching   •  Allows  the  request  for  a  generated  page  to  be   fulfilled  by  the  webserver,  without  ever  having   to  go  through  your  Rails  applicaFon.   Client   Apache   Mongrel   Public/users.html   hOp://localhost:3000/users  
  • 4. Page  Caching    Next  Fme  we  request  the  same  page,  apache   will  load  the  page  from  the  filesystem  and   send  it  back  to  the  client.   Client   Apache   Mongrel   Public/users.html  hOp://localhost:3000/users  
  • 5. When  we  might  want  to  page  cached?   •  When  every  user  always  sees  exactly  the  same   content  on  a  page,  even  if  they  are  login  to  the   admin  interface  or  not.  But  It's  always  the   same.   •  It  doesn't  change  so  oWen.  Maybe  once  per   day,  week  or  month.  
  • 6. Get  started  with  caching….   •  Make  sure   config.acFon_controller.perform_caching  is   set  to  true  for  your  environment.  (config/ environments/development.rb)   config.acFon_controller.perform_caching  =  true  
  • 8. Page  Caching  OpFons   •  format.json  {render  :json  =>  @users}   •  format.iphone   –  /config/iniFalizers/mime_types.rb   •  Mime::Type.register_alias  “text/html”,  :iphone   –  /app/views/users/index.iphone.erb   /public/users.html   /public/users.xml   /public/users.json   /public/users.iphone  
  • 10. Page  caching   •  Page  caching  ignores  all  parameters   – hOp://localhost:3000/users?page=1   Will  be  wriOen  out     so  if  someone  request   hOp://localhost:3000/users?page=3  it  will  be  gegng   users.html.  
  • 11. AcFon  Caching   •  Caching  stored     – Page  Caching   •  Stored  on  Disk   – AcFon  &  Fragment  Caching   •  Use  the  configured  cache  that  we  configure  in  our  rails   instance.    
  • 12. When  to  do  AcFon  Caching?     •  When  we  need  filters  to  run   – Like  authenFcaFon     Client   Apache   Mongrel   Public/posts.html   hOp://localhost:3000/posts   Run  Filters   (authenFcate)  
  • 14. AcFon  Caching   Didn’t  call  the  acFon.  It  loaded  straight  out  of  the  cache   It  executed  the  acFon  
  • 15. AcFon  Caching  OpFons   /config/environments/development.rb   •  config.cache_store  =  :file_store,  'tmp/cache’      (AcFveSupport::Cache::FileStore)     •  config.cache_store  =  :memory_store    (AcFveSupport::Cache::MemoryStore)     –  {}  in  memory  –background-­‐.  But  you  can  run  out  of  memory   –  No  sharing  between  processes.  You  cannot  use  it  if  you  run  more  than   one  instance  of  your  rails  apps.    
  • 16. AcFon  Caching  OpFons….   •  config.cache_store  =  :mem_cache_store   •  config.cache_store  =  :mem_cache_store,  :namespace  =>   “store”    (share  apps)   •  config.cache_store  =  :mem_cache_store,  192.168.1.255:1001,   192.168.1.255:1002  (mulFple  servers)    (AcFveSupport::Cache::MemCacheStore)     •  config.cache_store  =  :drb_store   (AcFveSupport::Cache::DRbStore)     •  config.cache_store  =  :custom_store  
  • 17. AcFon  Caching     •  Features   –  Cached  the  acFon  without  the  layout.   it  will  only  cache  your  acFon  content.   So,  if  you  need  some  sort  of  data  you  might  want  to  use   before_filter  and  set  you  instance  variable      
  • 18.
  • 19. AcFon  Caching     •  Features  (cont)   •  CondiFonal  AcFon  acFon  using  :if  (or  :unless)  =>  Proc.new{….}  to   specify  when  the  acFon  should  be  cached.     •  Specific  path  using  :cache_path  =>  Proc.new  {  |controller|  or   :cache_path  =>  <method>   :expires_in  =>1.hour  to  specify  when  the  acFon  should  be  cached.       (only  with  memcached  &  rails  >  2.1)  
  • 20. Fragment  Caching   •  Is  useful  for  dynamic  web  applicaFons   •  Allows  you  to  fragment  many  pieces  of  the  view.   The  pieces  will  be  wrapped  in  a  cache  block  and   served  out  of  the  cache  store  when  the  next   request  comes  in.     Client   Apache   Mongrel   header   hOp://localhost:3000/users   body   widgets  
  • 21. Fragment  Caching    To  implement  fragment  caching,  you  cache  your  method    in   the  view.   All  keys  are  prefixed  with  "views/"  
  • 22. Fragment  Caching   You  can  create  your  own  key:  <%  cache("#{@user.id}-­‐recents_joined")  do  %>  or   use  the  rails  way     <%  cache([user,  post,  “toolbar”])  do  %>  
  • 23. Memcached   •  Is  a  hash  in  memory,    key-­‐value  store    {}  in  memory   (LiveJournal)     –  To  implement  /config/environments/producFon.rb   config.cache_store  =  :mem_cache_store   Same  thing  as  config.cache_store  =  :memory_store     but  it  runs  as  a  separate  process.  You  can  have  several  rails   instances  that  references  the  same  mencached  instance     -­‐  Note:  make  sure  to  install  the  gem  memcached-­‐client.  
  • 24. Memcached  uses     •  Fragment  Cache  Store   •  AcFon  &  Fragment  Caching  
  • 25. Memcached  uses     •  As  an  Object  Store   –  Rails.cache.read   –  Rails.cache.write   –  Rails.cache.fetch   –  Rails.cache.delete   –  Rails.cache.exists?   –  Rails.cache.clear   –  Rails.cache.increment   –  Rails.cache.clear  
  • 27. Memcached  ….  Some  points:   -­‐  Expire  at   def  self.recent      Rails.cache.fetch("recent_posts",  :expires_in  =>  30.minutes)  do          self.find(:all,  :limit  =>  10)    end   end   Run  this  query  every  30  minutes…     -­‐    You  don’t  need  to  have  memcached  installed  to  develop  locally    You  will  get  MemCacheError  (No  connecFon  to  server):  No   connecFon  to  server  Cache  miss:    But,  your  app  will  work  just  fine.  Rails  will  always  execute  the   contents  of  the  fetch  blocks,  and  will  return  nil  for  any  reads.  
  • 28. Expiring  cached  pages   One’s  first  inclinaFon  may  be  to  expire  pages  in  the  Controller  and  usually  via  the   update  method.     Depending  on  which  technique  you  choose  to  expire  pages  you  can  use  the  method   expire_page  {acFon,fragment}   Instead  of  having  expire  methods  around  your  controllers,  to  clear  cache  files  based   on  when  a  model  is  updated,  sweepers  are  the  way  to  go.  
  • 29. Expiring  cached  page   AcFonController::Caching::Sweeper  class.  (Share  Objects)     –  Can  observe  Controllers   –  Can  observe  Models   Hooks:   Any  observer  callbacks    aWer  create    aWer  destroy    aWer_save,  etc.   Also  in  any  controllers  callbacks   •  before/aWer_<controller_name>   •  before/aWer_<controller_name>_<acFon>  
  • 30. Expiring  cached  page   To  implement  sweepers:    Declare  a  new  load  path  in  /config/environment.rb  to  keep  the  sweepers   separate  from  models  and  controllers.   config.load_paths  <<  "#{RAILS_ROOT}/app/sweepers”   Create  the  folder  and  the  observer  files  
  • 31. Expiring  cached  page   And  then  we  will  tell  the  controller  to  use  the  sweeper   cache_sweeper  :user_sweeper,  :only  =>  [:create,  :update,  :destroy]   When  to  call  the  method   Observe  the  model  
  • 33. Another  way  to  expire.   Clearing  the  cache   And  you  could  use  it  in  a  cron  call…  
  • 34. Some  thoughts    ImplemenFng  page  caching  can  be  easy.  However,  expiring  can  be   prove  to  be  a  bit  more  challenging  .   •  I  find  tesFng  kind  of  tricky.   •  I  read  through  numerous  blog  posts  but    I  couldn’t    quite  figure  out   how  to  get  things  to  work  as  I  hoped.     •  The  following  are  alternaFves  I’ve  recently  used:     –  Custom  Macthers  by  overwriFng  the  matches?  method   •  AcFonController::Caching::AcFons     –   Build  your  CachePage  /  Fragment  Page  class  and  use     •  AcFonController::Base.expire_page(    )   •  AcFonController::Caching::Fragments   –  expire_fragment   –  fragment_cache_key   –  fragment_exist?   –  read_fragment   –  write_fragment