SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
Memcached
Ken Collins <metaskills.net>
757.rb – July 14th 2009
About Memcached

Stands For "Memory Cache Daemon"
By Brad Fitzgerald, founder of LiveJournal
Introduced in October of 2003 to keep frequently-used
LiveJournal objects in memory. Including logins, colors,
styles, journal entries, commets, site text, etc.
Used by many major sites including Flickr, Slashdot,
Wikipedia and Facebook.
What Is Memcached (Or Not)
A server(s) that caches Name Value Pairs (NVPs) in
memory. This could be
NOT a persistent data store!
NOT queryable for a list of all objects. Only way to find
something is to ask for it by name. (by design)
No built-in security mechanisms.
No fail-over/high-availability mechanisms. (server goes
down, data is gone)
Memcached Layout
Basically Client <=> (NVP)Server
Server simple fast data retrival based on a key.
  Size of key can not exceed 250 characters.
  Size of value can not exceed 1 MB.
  Each memcached server is atomic. Neither knows or
  cares about any other memcached server.
Client libraries for most every major language. We will
focus on the Ruby client used by Rails.
Installation & Configuration

 Mac OS $   sudo port install memcached

 Others... pretty easy. Only dependency is libevent.
 (see http://danga.com/memcached/)
 Key arguments are -p, -m and -d. All using -h
 LaunchDaemon
 $ memcached -u nobody -m 512 -c 1024 -p 11211 -d
Styling & Profiling :)
 # Memcached
 alias mcconf="mate /opt/local/etc/LaunchDaemons/
 org.macports.memcached/memcached.wrapper"
 alias stopmc="sudo launchctl stop org.macports.memcached"
 alias startmc="sudo launchctl start org.macports.memcached"
 alias mcr="stopmc ; startmc"
Memcached
Basic Commands
ADD: Only store data if the key does NOT exist.
REPLACE: Only store data if the key ALREADY exists.
SET: Add or replace data.
GET: Return data.
INCR: Increment a counter.
DECR: Decrement a counter.
Rails With Memcached
Sessions. (config/initializers/session_store.rb)
ActionController::Base.session_store = :mem_cache_store, ‘localhost’

Everywhere Else! ActiveSupport::Cache (config/initializers/environments/*.rb)
config.action_controller.perform_caching = true
config.cache_store = :mem_cache_store

ActiveSupport::Cache Implementations:
   FileStore
   MemoryStore
   SynchronizedMemoryStore
   DRbStore
   MemCacheStore
   CompressedMemCacheStore


Accessible as Rails.cache
ActiveSupport::Cache Details
All implementations inherit from ActiveSupport::Cache::Store which define a
common simple interface.


 read(key, options = nil)
 write(key, value, options = nil)
 fetch(key, options = {})
 delete(key, options = nil)
 delete_matched(matcher, options = nil)
 exist?(key, options = nil)
 increment(key, amount = 1)
 decrement(key, amount = 1)
#read(key,options=nil)
cache.read("ids")                 #   =>   nil
cache.write("ids",[1,2,3])        #   =>   true
cache.read("ids")                 #   =>   [1, 2, 3]
cache.read("ids", :raw => true)   #   =>   "004b[bi006iaib"




#write(key,value,options=nil)
cache.write("foo", "bar", :expires_in => 5.seconds)
cache.read("foo") # => "bar"
sleep(6)
cache.read("foo") # => nil
#fetch(key,options={})
cache.write("today", "Tuesday")
cache.fetch("today") # => "Tuesday"

cache.fetch("city")    # => nil
cache.fetch("city") do
  "Duckburgh"
end
cache.fetch("city")    # => "Duckburgh"

cache.write("today", "Tuesday")
cache.fetch("today", :force => true)      # => nil

cache = ActiveSupport::Cache::MemCacheStore.new
cache.fetch("foo", :force => true, :expires_in => 5.seconds) do
  "bar"
end
cache.fetch("foo") # => "bar"
sleep(6)
cache.fetch("foo") # => nil
#delete(key,options=nil)
cache.write("ids",[1,2,3])      #   =>   true
cache.delete("ids")             #   =>   true
cache.read("ids")               #   =>   nil
cache.delete("notthere")        #   =>   false




#exist?(key,options=nil)
# Doesn't call super, cause exist? in memcached is in fact a read
# But who cares? Reading is very fast anyway.
!read(key, options).nil?
#increment(key,amount=1)
#decrement(key,amount=1)
cache.read("key")          #   =>   nil
cache.increment("key")     #   =>   nil
cache.write("key",20)      #   =>   true
cache.increment("key")     #   =>   1
cache.read("key")          #   =>   nil
cache.increment("key")     #   =>   2
cache.increment("key")     #   =>   3
cache.increment("key")     #   =>   4
cache.decrement("key")     #   =>   3
cache.increment("key",7)   #   =>   10
cache.decrement("key",5)   #   =>   5
MemCacheStore Specifics
 #clear – Performs a flush_all command on the
 memcached client. Deletes all data.
 #stats – Returns a server keyed hash built from each
 the memcached client’s server connection.

>> cache.stats
=> {"localhost:11211"=>{"get_hits"=>1518, "bytes"=>212577,
"rusage_system"=>0.890843, "pid"=>18081,
"connection_structures"=>11, "accepting_conns"=>1, "threads"=>5,
"limit_maxbytes"=>536870912, "evictions"=>0, "cmd_flush"=>1,
"pointer_size"=>32, "time"=>1247589002, "version"=>"1.2.8",
"listen_disabled_num"=>0, "bytes_written"=>191926,
"total_items"=>2191, "cmd_get"=>1883, "total_connections"=>12,
"curr_connections"=>10, "uptime"=>77901, "cmd_set"=>2191,
"rusage_user"=>0.438621, "bytes_read"=>269582, "get_misses"=>365,
"curr_items"=>1998}}
Going Deeper...
Multiple Servers
 Client implements a #get_server_for_key which
 determines a server hash and who gets the data.
 Lets make another server:
 $ memcached -u nobody -m 512 -p 11212 -U 11212 -d

Rails::Initializer.run do |config|
  #...
  config.cache_store = [:mem_cache_store,'localhost:11211','localhost:11212']
end

(1..1000).to_a.each { |n| Rails.cache.write(n.to_s,'somedata') }

Rails.cache.stats.each do |server,stats|
  puts "TotalItems [#{server}]: #{stats['total_items']}"
end

# TotalItems [localhost:11211]: 446
# TotalItems [localhost:11212]: 554
Client Compression
 Done. Thanks Rails.
 Just use :compressed_mem_cache_store

module ActiveSupport
  module Cache
    class CompressedMemCacheStore < MemCacheStore
      def read(name, options = nil)
        if value = super(name, (options || {}).merge(:raw => true))
          if raw?(options)
            value
          else
            Marshal.load(ActiveSupport::Gzip.decompress(value))
          end
        end
      end

      def write(name, value, options = nil)
        value = ActiveSupport::Gzip.compress(Marshal.dump(value)) unless raw?(options)
        super(name, value, (options || {}).merge(:raw => true))
      end
    end
  end
end
What To Cache?
Basic types like strings, integers, arrays or hashes. The
general rule is to consider the same objects that you
might put in a session, ignoring size.

cache.write "myarray", [1,2,3]   #   =>   true
a1 = cache.read("myarray")       #   =>   [1, 2,   3]
a2 = cache.read("myarray")       #   =>   [1, 2,   3]
a1.object_id == a2.object_id     #   =>   false
cache.read("myarray") << 4       #   =>   [1, 2,   3, 4]
cache.read("myarray")            #   =>   [1, 2,   3]

class MyClass
  attr_accessor :this, :that
end

mo = MyClass.new                 # => #<MyClass:0x26c7198>
mo.this = [1,2,3]
cache.write "myobject", mo       # ture
mo1 = cache.read("myobject")     # => #<MyClass:0x26ae6c0 @this=[1, 2, 3]>
mo1.this                         # => [1, 2, 3]
Caching In Action...
Live Discussion. Abstract:
 Review Nahum Wild’s Article on Spandex Memcached
 which is not part of Rails 2.3.
   http://www.motionstandingstill.com/spandex-memcache-store-is-now-in-rails-23/2009-02-04/
   https://rails.lighthouseapp.com/projects/8994/tickets/1653-per-request-in-memory-cache-for-all-communication-with-the-memcache-servers




 Review Nahum Wild’s Article on Starting Simple Rails
 Caching. Lesson is start with small line items vs page.
   http://www.motionstandingstill.com/starting-simple-with-rails-caching/2008-11-27/




 Demostrate The Above With “play_cache” rails app.
 Included in this keynote with screen highlights on next
 slide
Demo App

<h1>Articles#index</h1>

<table>
  <tr>
    <th>ID#</th>
    <th>User</th>
    <th>Title</th>
    <th>Comments</th>
    <th>Body</th>
  </tr>
  <% @articles.each do |article| %>
  <tr class="<%= cycle('even','odd') %>">
    <% cache(['list',article]) do %>
    <td class="center"><%= article.id %></td>
    <td class="center w50"><%= article.user.name %></td>
    <td class="center w150"><%= article.title %></td>
    <td class="center"><%= article.comments.count %></td>
    <td><%= truncate(article.body, :length => 50) %></td>
    <% end %>
  </tr>
  <% end %>
</table>
Other Resources

GUI Version Of Memcached For Mac
  http://github.com/andrewfromcali/mcinsight/tree/master


CacheMoney Rails Plugin
  http://github.com/nkallen/cache-money/tree/master

Weitere ähnliche Inhalte

Was ist angesagt?

Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
yiditushe
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance Django
DjangoCon2008
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012
Roland Bouman
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
guoqing75
 
Bottom to Top Stack Optimization - CICON2011
Bottom to Top Stack Optimization - CICON2011Bottom to Top Stack Optimization - CICON2011
Bottom to Top Stack Optimization - CICON2011
CodeIgniter Conference
 
Php user groupmemcached
Php user groupmemcachedPhp user groupmemcached
Php user groupmemcached
Jason Anderson
 
MongoDB: tips, trick and hacks
MongoDB: tips, trick and hacksMongoDB: tips, trick and hacks
MongoDB: tips, trick and hacks
Scott Hernandez
 

Was ist angesagt? (20)

Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
 
Nginx and friends - putting a turbo button on your site
Nginx and friends - putting a turbo button on your siteNginx and friends - putting a turbo button on your site
Nginx and friends - putting a turbo button on your site
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance Django
 
Cache is King - RubyHACK 2019
Cache is King - RubyHACK 2019Cache is King - RubyHACK 2019
Cache is King - RubyHACK 2019
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012
 
Nagios Conference 2013 - Sheeri Cabral - Alerting With MySQL and Nagios
Nagios Conference 2013 - Sheeri Cabral - Alerting With MySQL and NagiosNagios Conference 2013 - Sheeri Cabral - Alerting With MySQL and Nagios
Nagios Conference 2013 - Sheeri Cabral - Alerting With MySQL and Nagios
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
 
Bottom to Top Stack Optimization - CICON2011
Bottom to Top Stack Optimization - CICON2011Bottom to Top Stack Optimization - CICON2011
Bottom to Top Stack Optimization - CICON2011
 
Php user groupmemcached
Php user groupmemcachedPhp user groupmemcached
Php user groupmemcached
 
Beyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the codeBeyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the code
 
When dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniquesWhen dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniques
 
MongoDB: tips, trick and hacks
MongoDB: tips, trick and hacksMongoDB: tips, trick and hacks
MongoDB: tips, trick and hacks
 
MariaDB for developers
MariaDB for developersMariaDB for developers
MariaDB for developers
 
phptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorialphptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorial
 
My SQL 101
My SQL 101My SQL 101
My SQL 101
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
Hppg
HppgHppg
Hppg
 
Cache is King: Get the Most Bang for Your Buck From Ruby
Cache is King: Get the Most Bang for Your Buck From RubyCache is King: Get the Most Bang for Your Buck From Ruby
Cache is King: Get the Most Bang for Your Buck From Ruby
 

Andere mochten auch

WCIT 2012 - Assespro Oficial Bid Book
WCIT 2012 - Assespro Oficial Bid BookWCIT 2012 - Assespro Oficial Bid Book
WCIT 2012 - Assespro Oficial Bid Book
Assespro Nacional
 
Various hints & tips around Solution Selling (January 2014)
Various hints & tips aroundSolution Selling (January 2014)Various hints & tips aroundSolution Selling (January 2014)
Various hints & tips around Solution Selling (January 2014)
Eric Van 't Hoff
 
英文 Rc heli
英文 Rc heli英文 Rc heli
英文 Rc heli
tiffanysrc
 
The Evolution Of The Music Industry The Effect Of Technology And Law On Stra...
The Evolution Of The Music Industry  The Effect Of Technology And Law On Stra...The Evolution Of The Music Industry  The Effect Of Technology And Law On Stra...
The Evolution Of The Music Industry The Effect Of Technology And Law On Stra...
Ben Kilmer
 

Andere mochten auch (13)

WCIT 2012 - Assespro Oficial Bid Book
WCIT 2012 - Assespro Oficial Bid BookWCIT 2012 - Assespro Oficial Bid Book
WCIT 2012 - Assespro Oficial Bid Book
 
April 17, 2012 CIty Council Agenda Packet
April 17, 2012 CIty Council Agenda PacketApril 17, 2012 CIty Council Agenda Packet
April 17, 2012 CIty Council Agenda Packet
 
Safely Drinking from the Data Waterhose
Safely Drinking from the Data WaterhoseSafely Drinking from the Data Waterhose
Safely Drinking from the Data Waterhose
 
Various hints & tips around Solution Selling (January 2014)
Various hints & tips aroundSolution Selling (January 2014)Various hints & tips aroundSolution Selling (January 2014)
Various hints & tips around Solution Selling (January 2014)
 
Marco Hogewoning -XS4all
Marco Hogewoning -XS4allMarco Hogewoning -XS4all
Marco Hogewoning -XS4all
 
英文 Rc heli
英文 Rc heli英文 Rc heli
英文 Rc heli
 
Cybersecurity nl
Cybersecurity nlCybersecurity nl
Cybersecurity nl
 
4000 auto approve wordpress blogs backlink list (pr8-pr1)
4000 auto approve wordpress blogs backlink list (pr8-pr1)4000 auto approve wordpress blogs backlink list (pr8-pr1)
4000 auto approve wordpress blogs backlink list (pr8-pr1)
 
The Evolution Of The Music Industry The Effect Of Technology And Law On Stra...
The Evolution Of The Music Industry  The Effect Of Technology And Law On Stra...The Evolution Of The Music Industry  The Effect Of Technology And Law On Stra...
The Evolution Of The Music Industry The Effect Of Technology And Law On Stra...
 
Talk talk talk 2
Talk talk talk 2Talk talk talk 2
Talk talk talk 2
 
K TO 12 GRADE 7 LEARNING MATERIAL IN EDUKASYON SA PAGPAPAKATAO (Q1-Q2)
K TO 12 GRADE 7 LEARNING MATERIAL IN EDUKASYON SA PAGPAPAKATAO (Q1-Q2)K TO 12 GRADE 7 LEARNING MATERIAL IN EDUKASYON SA PAGPAPAKATAO (Q1-Q2)
K TO 12 GRADE 7 LEARNING MATERIAL IN EDUKASYON SA PAGPAPAKATAO (Q1-Q2)
 
88 Gibraltar i-remit collection procedure
88 Gibraltar i-remit collection procedure88 Gibraltar i-remit collection procedure
88 Gibraltar i-remit collection procedure
 
Netflix marketing plan
Netflix marketing plan Netflix marketing plan
Netflix marketing plan
 

Ähnlich wie Memcached Presentation @757rb

CHI-YAPC-2009
CHI-YAPC-2009CHI-YAPC-2009
CHI-YAPC-2009
jonswar
 
MySQL Scaling Presentation
MySQL Scaling PresentationMySQL Scaling Presentation
MySQL Scaling Presentation
Tommy Falgout
 

Ähnlich wie Memcached Presentation @757rb (20)

Memcached Study
Memcached StudyMemcached Study
Memcached Study
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
 
CHI-YAPC-2009
CHI-YAPC-2009CHI-YAPC-2009
CHI-YAPC-2009
 
(SDD402) Amazon ElastiCache Deep Dive | AWS re:Invent 2014
(SDD402) Amazon ElastiCache Deep Dive | AWS re:Invent 2014(SDD402) Amazon ElastiCache Deep Dive | AWS re:Invent 2014
(SDD402) Amazon ElastiCache Deep Dive | AWS re:Invent 2014
 
Bottom to Top Stack Optimization with LAMP
Bottom to Top Stack Optimization with LAMPBottom to Top Stack Optimization with LAMP
Bottom to Top Stack Optimization with LAMP
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
 
DataMapper
DataMapperDataMapper
DataMapper
 
Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011
 
Caching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTourCaching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTour
 
Scaling Your Cache
Scaling Your CacheScaling Your Cache
Scaling Your Cache
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
 
WiredTiger In-Memory vs WiredTiger B-Tree
WiredTiger In-Memory vs WiredTiger B-TreeWiredTiger In-Memory vs WiredTiger B-Tree
WiredTiger In-Memory vs WiredTiger B-Tree
 
DotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETDotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NET
 
About memcached
About memcachedAbout memcached
About memcached
 
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp KrennJavantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
 
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management....NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
 
Magic of Ruby
Magic of RubyMagic of Ruby
Magic of Ruby
 
Say YES to Premature Optimizations
Say YES to Premature OptimizationsSay YES to Premature Optimizations
Say YES to Premature Optimizations
 
(DAT407) Amazon ElastiCache: Deep Dive
(DAT407) Amazon ElastiCache: Deep Dive(DAT407) Amazon ElastiCache: Deep Dive
(DAT407) Amazon ElastiCache: Deep Dive
 
MySQL Scaling Presentation
MySQL Scaling PresentationMySQL Scaling Presentation
MySQL Scaling Presentation
 

Mehr von Ken Collins

Dominion Enterprises _H@&lt;k@th0n_
Dominion Enterprises _H@&lt;k@th0n_Dominion Enterprises _H@&lt;k@th0n_
Dominion Enterprises _H@&lt;k@th0n_
Ken Collins
 
Oo java script class construction
Oo java script class constructionOo java script class construction
Oo java script class construction
Ken Collins
 

Mehr von Ken Collins (7)

Secrets of the asset pipeline
Secrets of the asset pipelineSecrets of the asset pipeline
Secrets of the asset pipeline
 
Ruby struct
Ruby structRuby struct
Ruby struct
 
Dominion Enterprises _H@&lt;k@th0n_
Dominion Enterprises _H@&lt;k@th0n_Dominion Enterprises _H@&lt;k@th0n_
Dominion Enterprises _H@&lt;k@th0n_
 
Free The Enterprise With Ruby & Master Your Own Domain
Free The Enterprise With Ruby & Master Your Own DomainFree The Enterprise With Ruby & Master Your Own Domain
Free The Enterprise With Ruby & Master Your Own Domain
 
Oo java script class construction
Oo java script class constructionOo java script class construction
Oo java script class construction
 
Tool Time
Tool TimeTool Time
Tool Time
 
Synchronizing Core Data With Rails
Synchronizing Core Data With RailsSynchronizing Core Data With Rails
Synchronizing Core Data With Rails
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 

Memcached Presentation @757rb

  • 2. About Memcached Stands For "Memory Cache Daemon" By Brad Fitzgerald, founder of LiveJournal Introduced in October of 2003 to keep frequently-used LiveJournal objects in memory. Including logins, colors, styles, journal entries, commets, site text, etc. Used by many major sites including Flickr, Slashdot, Wikipedia and Facebook.
  • 3. What Is Memcached (Or Not) A server(s) that caches Name Value Pairs (NVPs) in memory. This could be NOT a persistent data store! NOT queryable for a list of all objects. Only way to find something is to ask for it by name. (by design) No built-in security mechanisms. No fail-over/high-availability mechanisms. (server goes down, data is gone)
  • 4. Memcached Layout Basically Client <=> (NVP)Server Server simple fast data retrival based on a key. Size of key can not exceed 250 characters. Size of value can not exceed 1 MB. Each memcached server is atomic. Neither knows or cares about any other memcached server. Client libraries for most every major language. We will focus on the Ruby client used by Rails.
  • 5. Installation & Configuration Mac OS $ sudo port install memcached Others... pretty easy. Only dependency is libevent. (see http://danga.com/memcached/) Key arguments are -p, -m and -d. All using -h LaunchDaemon $ memcached -u nobody -m 512 -c 1024 -p 11211 -d
  • 6. Styling & Profiling :) # Memcached alias mcconf="mate /opt/local/etc/LaunchDaemons/ org.macports.memcached/memcached.wrapper" alias stopmc="sudo launchctl stop org.macports.memcached" alias startmc="sudo launchctl start org.macports.memcached" alias mcr="stopmc ; startmc"
  • 7. Memcached Basic Commands ADD: Only store data if the key does NOT exist. REPLACE: Only store data if the key ALREADY exists. SET: Add or replace data. GET: Return data. INCR: Increment a counter. DECR: Decrement a counter.
  • 8. Rails With Memcached Sessions. (config/initializers/session_store.rb) ActionController::Base.session_store = :mem_cache_store, ‘localhost’ Everywhere Else! ActiveSupport::Cache (config/initializers/environments/*.rb) config.action_controller.perform_caching = true config.cache_store = :mem_cache_store ActiveSupport::Cache Implementations: FileStore MemoryStore SynchronizedMemoryStore DRbStore MemCacheStore CompressedMemCacheStore Accessible as Rails.cache
  • 9. ActiveSupport::Cache Details All implementations inherit from ActiveSupport::Cache::Store which define a common simple interface. read(key, options = nil) write(key, value, options = nil) fetch(key, options = {}) delete(key, options = nil) delete_matched(matcher, options = nil) exist?(key, options = nil) increment(key, amount = 1) decrement(key, amount = 1)
  • 10. #read(key,options=nil) cache.read("ids") # => nil cache.write("ids",[1,2,3]) # => true cache.read("ids") # => [1, 2, 3] cache.read("ids", :raw => true) # => "004b[bi006iaib" #write(key,value,options=nil) cache.write("foo", "bar", :expires_in => 5.seconds) cache.read("foo") # => "bar" sleep(6) cache.read("foo") # => nil
  • 11. #fetch(key,options={}) cache.write("today", "Tuesday") cache.fetch("today") # => "Tuesday" cache.fetch("city") # => nil cache.fetch("city") do "Duckburgh" end cache.fetch("city") # => "Duckburgh" cache.write("today", "Tuesday") cache.fetch("today", :force => true) # => nil cache = ActiveSupport::Cache::MemCacheStore.new cache.fetch("foo", :force => true, :expires_in => 5.seconds) do "bar" end cache.fetch("foo") # => "bar" sleep(6) cache.fetch("foo") # => nil
  • 12. #delete(key,options=nil) cache.write("ids",[1,2,3]) # => true cache.delete("ids") # => true cache.read("ids") # => nil cache.delete("notthere") # => false #exist?(key,options=nil) # Doesn't call super, cause exist? in memcached is in fact a read # But who cares? Reading is very fast anyway. !read(key, options).nil?
  • 13. #increment(key,amount=1) #decrement(key,amount=1) cache.read("key") # => nil cache.increment("key") # => nil cache.write("key",20) # => true cache.increment("key") # => 1 cache.read("key") # => nil cache.increment("key") # => 2 cache.increment("key") # => 3 cache.increment("key") # => 4 cache.decrement("key") # => 3 cache.increment("key",7) # => 10 cache.decrement("key",5) # => 5
  • 14. MemCacheStore Specifics #clear – Performs a flush_all command on the memcached client. Deletes all data. #stats – Returns a server keyed hash built from each the memcached client’s server connection. >> cache.stats => {"localhost:11211"=>{"get_hits"=>1518, "bytes"=>212577, "rusage_system"=>0.890843, "pid"=>18081, "connection_structures"=>11, "accepting_conns"=>1, "threads"=>5, "limit_maxbytes"=>536870912, "evictions"=>0, "cmd_flush"=>1, "pointer_size"=>32, "time"=>1247589002, "version"=>"1.2.8", "listen_disabled_num"=>0, "bytes_written"=>191926, "total_items"=>2191, "cmd_get"=>1883, "total_connections"=>12, "curr_connections"=>10, "uptime"=>77901, "cmd_set"=>2191, "rusage_user"=>0.438621, "bytes_read"=>269582, "get_misses"=>365, "curr_items"=>1998}}
  • 16. Multiple Servers Client implements a #get_server_for_key which determines a server hash and who gets the data. Lets make another server: $ memcached -u nobody -m 512 -p 11212 -U 11212 -d Rails::Initializer.run do |config| #... config.cache_store = [:mem_cache_store,'localhost:11211','localhost:11212'] end (1..1000).to_a.each { |n| Rails.cache.write(n.to_s,'somedata') } Rails.cache.stats.each do |server,stats| puts "TotalItems [#{server}]: #{stats['total_items']}" end # TotalItems [localhost:11211]: 446 # TotalItems [localhost:11212]: 554
  • 17. Client Compression Done. Thanks Rails. Just use :compressed_mem_cache_store module ActiveSupport module Cache class CompressedMemCacheStore < MemCacheStore def read(name, options = nil) if value = super(name, (options || {}).merge(:raw => true)) if raw?(options) value else Marshal.load(ActiveSupport::Gzip.decompress(value)) end end end def write(name, value, options = nil) value = ActiveSupport::Gzip.compress(Marshal.dump(value)) unless raw?(options) super(name, value, (options || {}).merge(:raw => true)) end end end end
  • 18. What To Cache? Basic types like strings, integers, arrays or hashes. The general rule is to consider the same objects that you might put in a session, ignoring size. cache.write "myarray", [1,2,3] # => true a1 = cache.read("myarray") # => [1, 2, 3] a2 = cache.read("myarray") # => [1, 2, 3] a1.object_id == a2.object_id # => false cache.read("myarray") << 4 # => [1, 2, 3, 4] cache.read("myarray") # => [1, 2, 3] class MyClass attr_accessor :this, :that end mo = MyClass.new # => #<MyClass:0x26c7198> mo.this = [1,2,3] cache.write "myobject", mo # ture mo1 = cache.read("myobject") # => #<MyClass:0x26ae6c0 @this=[1, 2, 3]> mo1.this # => [1, 2, 3]
  • 20. Live Discussion. Abstract: Review Nahum Wild’s Article on Spandex Memcached which is not part of Rails 2.3. http://www.motionstandingstill.com/spandex-memcache-store-is-now-in-rails-23/2009-02-04/ https://rails.lighthouseapp.com/projects/8994/tickets/1653-per-request-in-memory-cache-for-all-communication-with-the-memcache-servers Review Nahum Wild’s Article on Starting Simple Rails Caching. Lesson is start with small line items vs page. http://www.motionstandingstill.com/starting-simple-with-rails-caching/2008-11-27/ Demostrate The Above With “play_cache” rails app. Included in this keynote with screen highlights on next slide
  • 21. Demo App <h1>Articles#index</h1> <table> <tr> <th>ID#</th> <th>User</th> <th>Title</th> <th>Comments</th> <th>Body</th> </tr> <% @articles.each do |article| %> <tr class="<%= cycle('even','odd') %>"> <% cache(['list',article]) do %> <td class="center"><%= article.id %></td> <td class="center w50"><%= article.user.name %></td> <td class="center w150"><%= article.title %></td> <td class="center"><%= article.comments.count %></td> <td><%= truncate(article.body, :length => 50) %></td> <% end %> </tr> <% end %> </table>
  • 22. Other Resources GUI Version Of Memcached For Mac http://github.com/andrewfromcali/mcinsight/tree/master CacheMoney Rails Plugin http://github.com/nkallen/cache-money/tree/master