SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Redis, Resque and Friends




               Christopher Spring
         https://github.com/autonomous
                  @autonomous
          www.christopherspring.com
WTF is Redis?
WTF is Redis?


Remote Dictionary Server
Key-value storage...
   # Insert a value for a key
   SET some:key “value”

   # Retrieve value for a key
   GET some:key # => “value”
... on steroids!
# Lists
RPUSH chores "Mow lawn"
LPUSH chores "Get dressed"

# Sets
SADD sith "Darth Maul"
SUNION sith evil

# Sorted sets
ZADD background:workers 50 "w1.oss.com"
ZADD background:workers 19 "w3.oss.com"

# Hash
HMSET client username "womble" password "secret_womble"
HGET client password
Strings
Hashes
Lists
Sets
Sorted sets
$ brew install redis
$ redis-server /usr/local/etc/redis-conf
Example: Tagging
$ redis-cli
...
redis> SADD post:17:tag "ruby"
redis> SADD post:17:tag "rails"
redis> SADD post:17:tag "redis"

redis> SADD post:20:tag "resque"
redis> SADD post:20:tag "redis"

redis> SINTER post:17:tag post:20:tag
1. "redis"
Transactions
Example: Transactions
 $ redis-cli
 ...
 redis> SET "player:1:coins" 30
 redis> SET "player:2:coins" 63

 # ... Players decide to trade some coin

 redis> MULTI
 redis>   INCRBY "player:1:coins" 15
 redis>   DECRBY "player:2:coins" 15
 redis> EXEC

 # 1. (integer) 45
 # 2. (integer) 48
In-memory storage

 • Simple single process event
   driven design
 • No locks
 • 100K+ operations per second
Asynchronous persistence

  • Snapshotting -   save 60 1000
    # dump every 60 seconds if at least 1000
    keys changed


  • Append-only file - durable with log
    rewrite support
Master-slave replication
      slaveof '192.168.1.1' 6379



         • Multiple slaves
         • Slaves of slaves
         • Scalability
         • Defer save to
           slaves
... I’ve got too much data!
Redis Virtual Memory

  • Only values swapped to disk
  • Most recent values in memory
  • Predictable memory usage...
1M keys: 160 MB
10M keys: 1.6 GB
100M keys: 16 GB
MySQL + memcached



  • Multiple copies of data
  • Mainly scales reads
  • No higher level functions
Client libraries for all:
     •   C             •   Java

     •   C#            •   Lua

     •   C++           •   Node.js

     •   Clojure       •   Objective-c

     •   Common List   •   Perl

     •   Erlang        •   PHP

     •   Go            •   Python

     •   Haskell       •   Scala

     •   haXe          •   Smalltalk

     •   Io            •   Tcl
Client libraries for all:
     •   C             •   Java

     •   C#            •   Lua

     •   C++           •   Node.js

     •   Clojure       •   Objective-c

     •   Common List   •   Perl

     •   Erlang        •   PHP

     •   Go            •   Python

     •   Haskell       •   Scala

     •   haXe          •   Smalltalk

     •   Io            •   Tcl
$ sudo gem install redis
Redis as a database...
require 'rubygems'; require 'redis'; require 'json'

class RubyFuZa
  def initialize   args                                      class Dude < Struct.new(:first_name, :last_name); end
    @db        =   args[:db]
    @duration =    args[:duration] # seconds
    @namespace =   "#{self.class}:#{args[:id]}"              chris = Dude.new 'Chris', 'Spring'
    @s_key     =   "#{@namespace}:speakers"                  marc = Dude.new 'Marc', 'Heiligers'
    @a_key     =   "#{@namespace}:attendees"                 steve = Dude.new 'Steve', 'Hoffmeier' # Is jy my pa?
  end

  def start!                                                 redis    = Redis.new
    return "Already started!" if started?                    two_days = 2*24*60*60 # seconds
    @db[@namespace] = 'started'                              conf     = RubyFuZa.new(
    @db.expire( @namespace, @duration )                               :db => redis,
  end                                                                 :duration => two_days,
                                                                      :id => "2011")
  def started?
    @db[@namespace] == 'started'
  end                                                        conf.add_speaker chris # true
                                                             conf.add_attendee marc # true
  def how_much_longer?                                       conf.attendees         # [chris, marc]
    t = @db.ttl(@namespace)
    t == -1 ? 'It's over!' : t
  end                                                        conf.started?          # false
                                                             conf.start!            # true
  def add_speaker( speaker )                                 conf.started?          # true
    @db.sadd( @s_key, speaker.to_json )
  end
                                                             sleep( 2000 )
  def add_attendee( attendee )                               conf.how_much_longer? # two_days - 2000
    @db.sadd(@a_key, attendee.to_json)
  end

  def attendees
    @db.sinter(@s_key, @a_key).map{ |sa| JSON.parse( sa )}
  end
end
Publish/Subscribe
require 'rubygems'                             $ redis-cli
require "redis"                                ...
                                               redis> PUBLISH rubyfuza:chat "Smoke me a
redis = Redis.connect                          kipper..."
                                               redis> PUBLISH rubyfuza:chat "I'll be back
trap(:INT) { puts; exit }                      for breakfast."
                                               redis> PUBLISH rubyfuza:chat "exit"
redis.subscribe('rubyfuza:chat') do |on|
  on.subscribe do |channel, subscriptions|
    puts "Subscribed to ##{channel}"
  end

 on.message do |channel, message|
   puts "##{channel}: #{message}"
   redis.unsubscribe if message == "exit"
 end

  on.unsubscribe do |channel, subscriptions|
    puts "Unsubscribed from ##{channel}"
  end
end
Resque
• Backed by redis
• Asynchronous job server
• Multiple queues
• Sinatra based web-ui
class PostalWorker
  @queue :post_box

  def self.perform( user_id )
    User.where( :id => user_id )
    msg = UserMail.welcome_message( user )
    msg.deliver
  end
end

...

Resque.enqueue( PostalWorker, user.id )
Resque-Scheduler


• Queue jobs in the future!
• Recurring cron-style queueing
• Delayed jobs
database_cleaning:
  cron: "0 0 * * *"
  class: CleanupWorker
  args:
  description: "This jobs removes junk from the DB"
Resque.enqueue_at(
  5.days.from_now,
  SendFollowUpEmail,
  :user_id => current_user.id
)
Resque-retry

• Retry failed jobs
• Set number of retries
• Set delay between retries
• Exponential back-off
• Delays built on resque-scheduler
class WebHookWorker
  extend Resque::Plugins::Retry
  @queue = :web_hooks

  @retry_limit = 10
  @retry_delay = 5*60 # Seconds

  def self.perform(*args)
    # ... trigger web-hook
  end
end
In summary...
Data structure server

      • Strings
      • Hashes
      • Lists
      • Sets
      • Sorted sets
Main use cases:

    • Database
    • Cache
    • Messaging
Features:
• Fast
• Atomic operations
• Transactions
• Master-Slave
• Persist to disk
• Expiring keys
• Pub - Sub
• Redis Virtual Memory
Baie dankie!
Questions?
Links
• https://github.com/bblimke/copy-with-style-tmbundle
• http://redis.io/
• https://github.com/antirez/redis
• https://github.com/ezmobius/redis-rb
• http://antirez.com/
• https://github.com/defunkt/resque
• https://github.com/bvandenbos/resque-scheduler
• https://github.com/lantins/resque-retry

Weitere ähnliche Inhalte

Was ist angesagt?

Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboyKenneth Geisshirt
 
Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneC4Media
 
Linux shell scripting tutorial
Linux shell scripting tutorialLinux shell scripting tutorial
Linux shell scripting tutorialsamsami1971
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev ConfTom Croucher
 
Node.js streaming csv downloads proxy
Node.js streaming csv downloads proxyNode.js streaming csv downloads proxy
Node.js streaming csv downloads proxyIsmael Celis
 
Functional Hostnames and Why they are Bad
Functional Hostnames and Why they are BadFunctional Hostnames and Why they are Bad
Functional Hostnames and Why they are BadPuppet
 
Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)Itamar Haber
 
Zsh & fish: better *bash* for hackers
Zsh & fish: better *bash* for hackersZsh & fish: better *bash* for hackers
Zsh & fish: better *bash* for hackersRuslan Sharipov
 
Redis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational DatabasesRedis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational DatabasesKarel Minarik
 
(Practical) linux 104
(Practical) linux 104(Practical) linux 104
(Practical) linux 104Arie Bregman
 

Was ist angesagt? (17)

Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for Everyone
 
extending-php
extending-phpextending-php
extending-php
 
Linux shell scripting tutorial
Linux shell scripting tutorialLinux shell scripting tutorial
Linux shell scripting tutorial
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Node.js streaming csv downloads proxy
Node.js streaming csv downloads proxyNode.js streaming csv downloads proxy
Node.js streaming csv downloads proxy
 
Comredis
ComredisComredis
Comredis
 
Functional Hostnames and Why they are Bad
Functional Hostnames and Why they are BadFunctional Hostnames and Why they are Bad
Functional Hostnames and Why they are Bad
 
Linux Commands
Linux CommandsLinux Commands
Linux Commands
 
Configuration Management in Ansible
Configuration Management in Ansible Configuration Management in Ansible
Configuration Management in Ansible
 
Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)
 
Rpm Introduction
Rpm IntroductionRpm Introduction
Rpm Introduction
 
Zsh & fish: better *bash* for hackers
Zsh & fish: better *bash* for hackersZsh & fish: better *bash* for hackers
Zsh & fish: better *bash* for hackers
 
Redis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational DatabasesRedis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational Databases
 
Shell programming
Shell programmingShell programming
Shell programming
 
(Practical) linux 104
(Practical) linux 104(Practical) linux 104
(Practical) linux 104
 

Andere mochten auch

Redis as a message queue
Redis as a message queueRedis as a message queue
Redis as a message queueBrandon Lamb
 
How Cloudify uses Chef as a Foundation for PaaS
How Cloudify uses Chef as a Foundation for PaaSHow Cloudify uses Chef as a Foundation for PaaS
How Cloudify uses Chef as a Foundation for PaaSNati Shalom
 
AWS Sydney Summit 2013 - Optimizing AWS Applications and Usage to Reduce Costs
AWS Sydney Summit 2013 - Optimizing AWS Applications and Usage to Reduce CostsAWS Sydney Summit 2013 - Optimizing AWS Applications and Usage to Reduce Costs
AWS Sydney Summit 2013 - Optimizing AWS Applications and Usage to Reduce CostsAmazon Web Services
 
Realtime Big data Anaytics and Exampes of Daum (2013)
Realtime Big data Anaytics and Exampes of Daum (2013)Realtime Big data Anaytics and Exampes of Daum (2013)
Realtime Big data Anaytics and Exampes of Daum (2013)Channy Yun
 
Deview 2013 :: Backend PaaS, CloudFoundry 뽀개기
Deview 2013 :: Backend PaaS, CloudFoundry 뽀개기Deview 2013 :: Backend PaaS, CloudFoundry 뽀개기
Deview 2013 :: Backend PaaS, CloudFoundry 뽀개기Nanha Park
 
RestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueRestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueGleicon Moraes
 
Feb 2013 HUG: Large Scale Data Ingest Using Apache Flume
Feb 2013 HUG: Large Scale Data Ingest Using Apache FlumeFeb 2013 HUG: Large Scale Data Ingest Using Apache Flume
Feb 2013 HUG: Large Scale Data Ingest Using Apache FlumeYahoo Developer Network
 
REST vs. Messaging For Microservices
REST vs. Messaging For MicroservicesREST vs. Messaging For Microservices
REST vs. Messaging For MicroservicesEberhard Wolff
 

Andere mochten auch (10)

Steady with ruby
Steady with rubySteady with ruby
Steady with ruby
 
Php resque
Php resquePhp resque
Php resque
 
Redis as a message queue
Redis as a message queueRedis as a message queue
Redis as a message queue
 
How Cloudify uses Chef as a Foundation for PaaS
How Cloudify uses Chef as a Foundation for PaaSHow Cloudify uses Chef as a Foundation for PaaS
How Cloudify uses Chef as a Foundation for PaaS
 
AWS Sydney Summit 2013 - Optimizing AWS Applications and Usage to Reduce Costs
AWS Sydney Summit 2013 - Optimizing AWS Applications and Usage to Reduce CostsAWS Sydney Summit 2013 - Optimizing AWS Applications and Usage to Reduce Costs
AWS Sydney Summit 2013 - Optimizing AWS Applications and Usage to Reduce Costs
 
Realtime Big data Anaytics and Exampes of Daum (2013)
Realtime Big data Anaytics and Exampes of Daum (2013)Realtime Big data Anaytics and Exampes of Daum (2013)
Realtime Big data Anaytics and Exampes of Daum (2013)
 
Deview 2013 :: Backend PaaS, CloudFoundry 뽀개기
Deview 2013 :: Backend PaaS, CloudFoundry 뽀개기Deview 2013 :: Backend PaaS, CloudFoundry 뽀개기
Deview 2013 :: Backend PaaS, CloudFoundry 뽀개기
 
RestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueRestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message Queue
 
Feb 2013 HUG: Large Scale Data Ingest Using Apache Flume
Feb 2013 HUG: Large Scale Data Ingest Using Apache FlumeFeb 2013 HUG: Large Scale Data Ingest Using Apache Flume
Feb 2013 HUG: Large Scale Data Ingest Using Apache Flume
 
REST vs. Messaging For Microservices
REST vs. Messaging For MicroservicesREST vs. Messaging For Microservices
REST vs. Messaging For Microservices
 

Ähnlich wie Redis, Resque & Friends

Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Wen-Tien Chang
 
Redis for your boss 2.0
Redis for your boss 2.0Redis for your boss 2.0
Redis for your boss 2.0Elena Kolevska
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perlworr1244
 
DRb and Rinda
DRb and RindaDRb and Rinda
DRb and RindaMark
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Wen-Tien Chang
 
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxRubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxDr Nic Williams
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redisjimbojsb
 
Advanced Technology for Web Application Design
Advanced Technology for Web Application DesignAdvanced Technology for Web Application Design
Advanced Technology for Web Application DesignBryce Kerley
 
Perl on Amazon Elastic MapReduce
Perl on Amazon Elastic MapReducePerl on Amazon Elastic MapReduce
Perl on Amazon Elastic MapReducePedro Figueiredo
 
Stack kicker devopsdays-london-2013
Stack kicker devopsdays-london-2013Stack kicker devopsdays-london-2013
Stack kicker devopsdays-london-2013Simon McCartney
 
并发模型介绍
并发模型介绍并发模型介绍
并发模型介绍qiang
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Brian Hogan
 
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and RailsAnchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and RailsEleanor McHugh
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Henry S
 
Linux Shell Scripting Craftsmanship
Linux Shell Scripting CraftsmanshipLinux Shell Scripting Craftsmanship
Linux Shell Scripting Craftsmanshipbokonen
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable LispAstrails
 
Rails 3 (beta) Roundup
Rails 3 (beta) RoundupRails 3 (beta) Roundup
Rails 3 (beta) RoundupWayne Carter
 

Ähnlich wie Redis, Resque & Friends (20)

Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
 
Redis for your boss 2.0
Redis for your boss 2.0Redis for your boss 2.0
Redis for your boss 2.0
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
DRb and Rinda
DRb and RindaDRb and Rinda
DRb and Rinda
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxRubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
 
Redis
RedisRedis
Redis
 
Advanced Technology for Web Application Design
Advanced Technology for Web Application DesignAdvanced Technology for Web Application Design
Advanced Technology for Web Application Design
 
Perl on Amazon Elastic MapReduce
Perl on Amazon Elastic MapReducePerl on Amazon Elastic MapReduce
Perl on Amazon Elastic MapReduce
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Stack kicker devopsdays-london-2013
Stack kicker devopsdays-london-2013Stack kicker devopsdays-london-2013
Stack kicker devopsdays-london-2013
 
并发模型介绍
并发模型介绍并发模型介绍
并发模型介绍
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7
 
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and RailsAnchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2
 
Linux Shell Scripting Craftsmanship
Linux Shell Scripting CraftsmanshipLinux Shell Scripting Craftsmanship
Linux Shell Scripting Craftsmanship
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable Lisp
 
Rails 3 (beta) Roundup
Rails 3 (beta) RoundupRails 3 (beta) Roundup
Rails 3 (beta) Roundup
 

Mehr von Christopher Spring

Mehr von Christopher Spring (6)

jRuby and TorqueBox
jRuby and TorqueBoxjRuby and TorqueBox
jRuby and TorqueBox
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worlds
 
EventMachine for RubyFuZa 2012
EventMachine for RubyFuZa   2012EventMachine for RubyFuZa   2012
EventMachine for RubyFuZa 2012
 
Ruby Concurrency and EventMachine
Ruby Concurrency and EventMachineRuby Concurrency and EventMachine
Ruby Concurrency and EventMachine
 
Redis overview for Software Architecture Forum
Redis overview for Software Architecture ForumRedis overview for Software Architecture Forum
Redis overview for Software Architecture Forum
 
Ohm
OhmOhm
Ohm
 

Kürzlich hochgeladen

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 DevelopmentsTrustArc
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
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, ...apidays
 
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 Scriptwesley chun
 
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 educationjfdjdjcjdnsjd
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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?Igalia
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
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 TerraformAndrey Devyatkin
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 

Kürzlich hochgeladen (20)

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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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, ...
 
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
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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?
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
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
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

Redis, Resque & Friends

  • 1. Redis, Resque and Friends Christopher Spring https://github.com/autonomous @autonomous www.christopherspring.com
  • 3. WTF is Redis? Remote Dictionary Server
  • 4. Key-value storage... # Insert a value for a key SET some:key “value” # Retrieve value for a key GET some:key # => “value”
  • 5. ... on steroids! # Lists RPUSH chores "Mow lawn" LPUSH chores "Get dressed" # Sets SADD sith "Darth Maul" SUNION sith evil # Sorted sets ZADD background:workers 50 "w1.oss.com" ZADD background:workers 19 "w3.oss.com" # Hash HMSET client username "womble" password "secret_womble" HGET client password
  • 11. $ brew install redis $ redis-server /usr/local/etc/redis-conf
  • 12. Example: Tagging $ redis-cli ... redis> SADD post:17:tag "ruby" redis> SADD post:17:tag "rails" redis> SADD post:17:tag "redis" redis> SADD post:20:tag "resque" redis> SADD post:20:tag "redis" redis> SINTER post:17:tag post:20:tag 1. "redis"
  • 14. Example: Transactions $ redis-cli ... redis> SET "player:1:coins" 30 redis> SET "player:2:coins" 63 # ... Players decide to trade some coin redis> MULTI redis> INCRBY "player:1:coins" 15 redis> DECRBY "player:2:coins" 15 redis> EXEC # 1. (integer) 45 # 2. (integer) 48
  • 15. In-memory storage • Simple single process event driven design • No locks • 100K+ operations per second
  • 16. Asynchronous persistence • Snapshotting - save 60 1000 # dump every 60 seconds if at least 1000 keys changed • Append-only file - durable with log rewrite support
  • 17. Master-slave replication slaveof '192.168.1.1' 6379 • Multiple slaves • Slaves of slaves • Scalability • Defer save to slaves
  • 18. ... I’ve got too much data!
  • 19. Redis Virtual Memory • Only values swapped to disk • Most recent values in memory • Predictable memory usage...
  • 20. 1M keys: 160 MB 10M keys: 1.6 GB 100M keys: 16 GB
  • 21.
  • 22. MySQL + memcached • Multiple copies of data • Mainly scales reads • No higher level functions
  • 23. Client libraries for all: • C • Java • C# • Lua • C++ • Node.js • Clojure • Objective-c • Common List • Perl • Erlang • PHP • Go • Python • Haskell • Scala • haXe • Smalltalk • Io • Tcl
  • 24. Client libraries for all: • C • Java • C# • Lua • C++ • Node.js • Clojure • Objective-c • Common List • Perl • Erlang • PHP • Go • Python • Haskell • Scala • haXe • Smalltalk • Io • Tcl
  • 25. $ sudo gem install redis
  • 26. Redis as a database...
  • 27. require 'rubygems'; require 'redis'; require 'json' class RubyFuZa def initialize args class Dude < Struct.new(:first_name, :last_name); end @db = args[:db] @duration = args[:duration] # seconds @namespace = "#{self.class}:#{args[:id]}" chris = Dude.new 'Chris', 'Spring' @s_key = "#{@namespace}:speakers" marc = Dude.new 'Marc', 'Heiligers' @a_key = "#{@namespace}:attendees" steve = Dude.new 'Steve', 'Hoffmeier' # Is jy my pa? end def start! redis = Redis.new return "Already started!" if started? two_days = 2*24*60*60 # seconds @db[@namespace] = 'started' conf = RubyFuZa.new( @db.expire( @namespace, @duration ) :db => redis, end :duration => two_days, :id => "2011") def started? @db[@namespace] == 'started' end conf.add_speaker chris # true conf.add_attendee marc # true def how_much_longer? conf.attendees # [chris, marc] t = @db.ttl(@namespace) t == -1 ? 'It's over!' : t end conf.started? # false conf.start! # true def add_speaker( speaker ) conf.started? # true @db.sadd( @s_key, speaker.to_json ) end sleep( 2000 ) def add_attendee( attendee ) conf.how_much_longer? # two_days - 2000 @db.sadd(@a_key, attendee.to_json) end def attendees @db.sinter(@s_key, @a_key).map{ |sa| JSON.parse( sa )} end end
  • 29. require 'rubygems' $ redis-cli require "redis" ... redis> PUBLISH rubyfuza:chat "Smoke me a redis = Redis.connect kipper..." redis> PUBLISH rubyfuza:chat "I'll be back trap(:INT) { puts; exit } for breakfast." redis> PUBLISH rubyfuza:chat "exit" redis.subscribe('rubyfuza:chat') do |on| on.subscribe do |channel, subscriptions| puts "Subscribed to ##{channel}" end on.message do |channel, message| puts "##{channel}: #{message}" redis.unsubscribe if message == "exit" end on.unsubscribe do |channel, subscriptions| puts "Unsubscribed from ##{channel}" end end
  • 30. Resque • Backed by redis • Asynchronous job server • Multiple queues • Sinatra based web-ui
  • 31. class PostalWorker @queue :post_box def self.perform( user_id ) User.where( :id => user_id ) msg = UserMail.welcome_message( user ) msg.deliver end end ... Resque.enqueue( PostalWorker, user.id )
  • 32. Resque-Scheduler • Queue jobs in the future! • Recurring cron-style queueing • Delayed jobs
  • 33. database_cleaning: cron: "0 0 * * *" class: CleanupWorker args: description: "This jobs removes junk from the DB"
  • 34. Resque.enqueue_at( 5.days.from_now, SendFollowUpEmail, :user_id => current_user.id )
  • 35. Resque-retry • Retry failed jobs • Set number of retries • Set delay between retries • Exponential back-off • Delays built on resque-scheduler
  • 36. class WebHookWorker extend Resque::Plugins::Retry @queue = :web_hooks @retry_limit = 10 @retry_delay = 5*60 # Seconds def self.perform(*args) # ... trigger web-hook end end
  • 38. Data structure server • Strings • Hashes • Lists • Sets • Sorted sets
  • 39. Main use cases: • Database • Cache • Messaging
  • 40. Features: • Fast • Atomic operations • Transactions • Master-Slave • Persist to disk • Expiring keys • Pub - Sub • Redis Virtual Memory
  • 43. Links • https://github.com/bblimke/copy-with-style-tmbundle • http://redis.io/ • https://github.com/antirez/redis • https://github.com/ezmobius/redis-rb • http://antirez.com/ • https://github.com/defunkt/resque • https://github.com/bvandenbos/resque-scheduler • https://github.com/lantins/resque-retry

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n