SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Downloaden Sie, um offline zu lesen
Redis and Ruby




Brian Kaney
IRC / github / twitter / quora / etc : bkaney
Developer at Vermonster <vermonster.com>
Haven't we heard Redis Talks
                  Before?
●   Yes, Redis is popular
●   Why is this different?
    ●   Not covering Resque, Caching, Sessions or even
        Pub/Sub
    ●   Usage of Redis to store Ruby objects
    ●   Why would you want to do that?
Quick Redis 101 - Datatypes
●   Keys are strings, no need to quote
●   Strings
●   Integers (not really- INCR is a string operation)
●   Lists
●   Sets
●   Sorted Sets (sets with a score)
●   http://redis.oi (interactive terminal; website
    written in cuba.io, incidentally)
Let's talk Ruby
●   Ruby has strings, hashes, arrays..
●   And hashes are many times used as data
    storage for Ruby objects..
●   Wouldn't it be nice to use Redis to persist Ruby
    objects?
Redis-rb
●   Download and install redis   http://redis.io/download
●   Install ruby gem
    $ gem install redis
●   Connection
    require 'redis'
    db = Redis.new
Ruby Serialization                        *
●   Suppose a simple hash
     movie = Hash[
         :name, 'Top Gun',
         :genre, 'Action'
     ]


●   Might be represented in redis as:
    db.hmset 'movie:1', 'name', 'Top Gun', 'genre', 'Action'
Auto-increment ID
●   Notice incrementing in the key name
    db.hmset 'movie:1', 'name', 'Top Gun', 'genre', 'Action'



●   Create tooling to track id's, we can use INCR
    def get_pk(item, db)
       pk = db.incr "#{item}:pk"
       "#{item}:#{pk}"
    end


    db.hmset get_pk('movies', db), 'name', 'Top Gun', ...
References
●   A reference, like in AR 'belongs_to'

●   Could be implemented similarly:
    db.hmset 'character:1', 'movie_id', 'movie:1'
Has Many
●   Embed as one of the keys
# Make a few jets
db.hmset 'jet:1', 'manufacturer', 'Grumman', 'model', 'F-14'

db.hmset 'jet:2', 'manufacturer', 'Northrop', 'model', 'F-5'



# Make our movie
db.hmset 'movie:1', 'jets', %w(jet:1 jet:2).to_json
Has Many (set)
●   But that's not really “redisy”
●   How about conceiving a new key name and creating a set?
    # Make a few jets
    db.hmset 'jet:1', 'manufacturer', 'Grumman', 'model', 'F-14'
    db.hmset 'jet:2', 'manufacturer', 'Northrop', 'model', 'F-5'


    # Make our movie
    db.hmset 'movie:1', 'name', 'Top Gun', 'genre', 'Action'


    # Add to a key to represent the set of jets
    db.sadd 'movie:1:jets', 'jet:1'
    db.sadd 'movie:1:jets', 'jet:2'
Find / Indexing
●   Finding items, need an index.
●   Indexes could be sets with prescribed keys.
    # Create a few movies
    db.hmset 'movie:1', 'name', 'Top Gun', 'genre', 'Action'
    db.hmset 'movie:2', 'name', 'Top Gun', 'genre', 'Action'
    db.hmset 'movie:3', 'name', 'Airplane', 'genre', 'Comedy'



    # Create an index on 'genre'
    db.sadd 'movie:index:genre:Action', 'movie:1'
    db.sadd 'movie:index:genre:Action', 'movie:2'
    db.sadd 'movie:index:genre:Comedy', 'movie:3'
Yikes!
We need a Key Strategy
●   Among other things...
Nest
●   Very simple convention
       <klass.underscore>:<identifier>
       movie:1
       jet:10
       character:iceman


●   https://github.com/soveran/nest/blob/master/lib/nest.rb
We need tooling to manage
             relationships
●   Nest gives nice convention for key, but what
    about sets, lists, references, indexes,
    collections, validation, callbacks, etc...

●   Enter Ohm

●   https://github.com/soveran/ohm
Ohm: Redis-Ruby Object Hash Mapper
●   Ohm models for movies, characters and jets.
    (see code)
Using Ohm (example)
(code)
Devops - AOF
●   AOF is a newish strategy for managing data.
●   Configuration (redis.conf):
        appendonly yes
        appendfilename appendonly.aof
●   Process to save is:
    ●   issue 'BGREWRITEAOF'
    ●   loop until complete
●   Process to load is:
    ●   stop redis
    ●   copy AOF file to prescribed location (redis.conf)
    ●   loop until loading is complete
Devops – AOF save
  %x{ echo "BGREWRITEAOF" | redis-cli }
  loop do
        sleep 1
        puts " * Waiting for aof to save..."
       save_status = %x{ echo "INFO" | redis-cli | grep
bgrewriteaof_in_progress }[/:([0-9])/,1]
        break if save_status == "0"
  end
  puts "DONE!"
Devops – AOF load
  loop do
        sleep 1
        puts " * Waiting for aof to load..."
       load_status = %x{ echo "INFO" | redis-cli | grep
loading }[/:([0-9])/,1]
        break if load_status == "0"
  end
  puts "DONE"
Devops - Sockets
●   Faster, no TCP overhead
●   Configuration (redis.conf)
      # port 6379
      unixsocket /tmp/redis.sock
●   Redis-cli
      $ redis-cli -s /tmp/redis.sock
●   Redis.rb
      Redis.new(:path => '/tmp/redis.sock')
Ohm::Contrib
    https://github.com/sinefunc/ohm-contrib
●   Ohm::Boundaries
●   Ohm::Callbacks
●   Ohm::Timestamping
●   Ohm::ToHash
●   Ohm::WebValidations
●   Ohm::NumberValidations
●   Ohm::ExtraValidations
●   Ohm::Typecast
●   Ohm::Locking
Ohm::Contrib is hacky
ruby-1.9.2-p180 :016 > os = Ohm::Types::String.new "key"; s = "key"
ruby-1.9.2-p180 :018 > os == s
 => true
ruby-1.9.2-p180 :019 > os === s
 => true
ruby-1.9.2-p180 :020 > hsh = { os => 'foo' }
 => {"key"=>"foo"}
ruby-1.9.2-p180 :021 > hsh[os]
 => "foo"
ruby-1.9.2-p180 :022 > hsh[s]
 => nil
Hacks - Overriding redis_id
require 'ohm'
class Ohm
 class Model
  # initialize: added ability to pass redis_id and have it define the actual Ohm ID. (new? is broken in Ohm, BTW)
  alias_method :initialize_without_redis_id, :initialize
  def initialize_with_redis_id(args={})
   @redis_id = args.delete(:redis_id)
   initialize_without_redis_id(args)
  end
  alias_method :initialize, :initialize_with_redis_id


  def initialize_id
   @id ||= (@redis_id || self.class.key[:id].incr.to_s)
  end
  private :initialize_id
end
Hacks – Adding list/set by id
●    Default to have the Ohm saved, use <<
●    We wanted to pass in id, since we prescribed them anyway.
class List
     def push_id(model_id)
      key.rpush(model_id)
     end
    end
    class Set
     def push_id(model_id)
      key.sadd(model_id)
     end
    end
Thanks

Weitere ähnliche Inhalte

Was ist angesagt?

Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevFelix Geisendörfer
 
Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneC4Media
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Felix Geisendörfer
 
Perl Memory Use 201207 (OUTDATED, see 201209 )
Perl Memory Use 201207 (OUTDATED, see 201209 )Perl Memory Use 201207 (OUTDATED, see 201209 )
Perl Memory Use 201207 (OUTDATED, see 201209 )Tim Bunce
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)Felix Geisendörfer
 
Introduction to redis - version 2
Introduction to redis - version 2Introduction to redis - version 2
Introduction to redis - version 2Dvir Volk
 
COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?Lloyd Huang
 
Dirty - How simple is your database?
Dirty - How simple is your database?Dirty - How simple is your database?
Dirty - How simple is your database?Felix Geisendörfer
 
Empacotamento e backport de aplicações em debian
Empacotamento e backport de aplicações em debianEmpacotamento e backport de aplicações em debian
Empacotamento e backport de aplicações em debianAndre Ferraz
 
GlusterFS As an Object Storage
GlusterFS As an Object StorageGlusterFS As an Object Storage
GlusterFS As an Object StorageKeisuke Takahashi
 
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
 

Was ist angesagt? (20)

Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Node.js in production
Node.js in productionNode.js in production
Node.js in production
 
Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3
 
Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for Everyone
 
Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?
 
Perl Memory Use 201207 (OUTDATED, see 201209 )
Perl Memory Use 201207 (OUTDATED, see 201209 )Perl Memory Use 201207 (OUTDATED, see 201209 )
Perl Memory Use 201207 (OUTDATED, see 201209 )
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)
 
Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)
 
Node.js - A Quick Tour II
Node.js - A Quick Tour IINode.js - A Quick Tour II
Node.js - A Quick Tour II
 
Introduction to redis - version 2
Introduction to redis - version 2Introduction to redis - version 2
Introduction to redis - version 2
 
COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?
 
Node.js - As a networking tool
Node.js - As a networking toolNode.js - As a networking tool
Node.js - As a networking tool
 
Dirty - How simple is your database?
Dirty - How simple is your database?Dirty - How simple is your database?
Dirty - How simple is your database?
 
Empacotamento e backport de aplicações em debian
Empacotamento e backport de aplicações em debianEmpacotamento e backport de aplicações em debian
Empacotamento e backport de aplicações em debian
 
Redis acc
Redis accRedis acc
Redis acc
 
GlusterFS As an Object Storage
GlusterFS As an Object StorageGlusterFS As an Object Storage
GlusterFS As an Object Storage
 
Nginx-lua
Nginx-luaNginx-lua
Nginx-lua
 
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
 
Comredis
ComredisComredis
Comredis
 

Ähnlich wie Serializing Ruby Objects in Redis

Redis and its many use cases
Redis and its many use casesRedis and its many use cases
Redis and its many use casesChristian Joudrey
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby TeamArto Artnik
 
Gem That (2009)
Gem That (2009)Gem That (2009)
Gem That (2009)lazyatom
 
RHCSA EX200 - Summary
RHCSA EX200 - SummaryRHCSA EX200 - Summary
RHCSA EX200 - SummaryNugroho Gito
 
Feb 2018 Spinnaker Meetup Reddit Presentation
Feb 2018 Spinnaker Meetup Reddit PresentationFeb 2018 Spinnaker Meetup Reddit Presentation
Feb 2018 Spinnaker Meetup Reddit PresentationEdward Ceaser
 
Ruby C extensions at the Ruby drink-up of Sophia, April 2012
Ruby C extensions at the Ruby drink-up of Sophia, April 2012Ruby C extensions at the Ruby drink-up of Sophia, April 2012
Ruby C extensions at the Ruby drink-up of Sophia, April 2012rivierarb
 
Practical Testing of Ruby Core
Practical Testing of Ruby CorePractical Testing of Ruby Core
Practical Testing of Ruby CoreHiroshi SHIBATA
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsDerek Anderson
 
[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview
[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview
[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis OverviewLeo Lorieri
 
Boxen: How to Manage an Army of Laptops
Boxen: How to Manage an Army of LaptopsBoxen: How to Manage an Army of Laptops
Boxen: How to Manage an Army of LaptopsPuppet
 
Perl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one linersPerl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one linersKirk Kimmel
 
One-Liners to Rule Them All
One-Liners to Rule Them AllOne-Liners to Rule Them All
One-Liners to Rule Them Allegypt
 
Automate with Ansible basic (2/e, English)
Automate with Ansible basic (2/e, English)Automate with Ansible basic (2/e, English)
Automate with Ansible basic (2/e, English)Chu-Siang Lai
 
Crafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in RubyCrafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in RubyNikhil Mungel
 
Node.js - The New, New Hotness
Node.js - The New, New HotnessNode.js - The New, New Hotness
Node.js - The New, New HotnessDaniel Shaw
 
Ansible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife OrchestrationAnsible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife Orchestrationbcoca
 
Rocket Fuelled Cucumbers
Rocket Fuelled CucumbersRocket Fuelled Cucumbers
Rocket Fuelled CucumbersJoseph Wilk
 

Ähnlich wie Serializing Ruby Objects in Redis (20)

Redis and its many use cases
Redis and its many use casesRedis and its many use cases
Redis and its many use cases
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby Team
 
Gem That (2009)
Gem That (2009)Gem That (2009)
Gem That (2009)
 
RHCSA EX200 - Summary
RHCSA EX200 - SummaryRHCSA EX200 - Summary
RHCSA EX200 - Summary
 
Feb 2018 Spinnaker Meetup Reddit Presentation
Feb 2018 Spinnaker Meetup Reddit PresentationFeb 2018 Spinnaker Meetup Reddit Presentation
Feb 2018 Spinnaker Meetup Reddit Presentation
 
Ruby C extensions at the Ruby drink-up of Sophia, April 2012
Ruby C extensions at the Ruby drink-up of Sophia, April 2012Ruby C extensions at the Ruby drink-up of Sophia, April 2012
Ruby C extensions at the Ruby drink-up of Sophia, April 2012
 
Smalltalk on rubinius
Smalltalk on rubiniusSmalltalk on rubinius
Smalltalk on rubinius
 
Practical Testing of Ruby Core
Practical Testing of Ruby CorePractical Testing of Ruby Core
Practical Testing of Ruby Core
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCats
 
[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview
[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview
[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview
 
Boxen: How to Manage an Army of Laptops
Boxen: How to Manage an Army of LaptopsBoxen: How to Manage an Army of Laptops
Boxen: How to Manage an Army of Laptops
 
Perl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one linersPerl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one liners
 
One-Liners to Rule Them All
One-Liners to Rule Them AllOne-Liners to Rule Them All
One-Liners to Rule Them All
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Automate with Ansible basic (2/e, English)
Automate with Ansible basic (2/e, English)Automate with Ansible basic (2/e, English)
Automate with Ansible basic (2/e, English)
 
Docker, c'est bonheur !
Docker, c'est bonheur !Docker, c'est bonheur !
Docker, c'est bonheur !
 
Crafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in RubyCrafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in Ruby
 
Node.js - The New, New Hotness
Node.js - The New, New HotnessNode.js - The New, New Hotness
Node.js - The New, New Hotness
 
Ansible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife OrchestrationAnsible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife Orchestration
 
Rocket Fuelled Cucumbers
Rocket Fuelled CucumbersRocket Fuelled Cucumbers
Rocket Fuelled Cucumbers
 

Mehr von Brian Kaney

Continuous Delivery
Continuous DeliveryContinuous Delivery
Continuous DeliveryBrian Kaney
 
Newer Yankee Workshop - NoSQL
Newer Yankee Workshop -  NoSQLNewer Yankee Workshop -  NoSQL
Newer Yankee Workshop - NoSQLBrian Kaney
 
Build-a-Gem Workshop
Build-a-Gem WorkshopBuild-a-Gem Workshop
Build-a-Gem WorkshopBrian Kaney
 
Build-a-Gem Workshop
Build-a-Gem WorkshopBuild-a-Gem Workshop
Build-a-Gem WorkshopBrian Kaney
 
Bostonrb Amazon Talk
Bostonrb Amazon TalkBostonrb Amazon Talk
Bostonrb Amazon TalkBrian Kaney
 

Mehr von Brian Kaney (6)

Continuous Delivery
Continuous DeliveryContinuous Delivery
Continuous Delivery
 
Rest
RestRest
Rest
 
Newer Yankee Workshop - NoSQL
Newer Yankee Workshop -  NoSQLNewer Yankee Workshop -  NoSQL
Newer Yankee Workshop - NoSQL
 
Build-a-Gem Workshop
Build-a-Gem WorkshopBuild-a-Gem Workshop
Build-a-Gem Workshop
 
Build-a-Gem Workshop
Build-a-Gem WorkshopBuild-a-Gem Workshop
Build-a-Gem Workshop
 
Bostonrb Amazon Talk
Bostonrb Amazon TalkBostonrb Amazon Talk
Bostonrb Amazon Talk
 

Kürzlich hochgeladen

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Kürzlich hochgeladen (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Serializing Ruby Objects in Redis

  • 1. Redis and Ruby Brian Kaney IRC / github / twitter / quora / etc : bkaney Developer at Vermonster <vermonster.com>
  • 2. Haven't we heard Redis Talks Before? ● Yes, Redis is popular ● Why is this different? ● Not covering Resque, Caching, Sessions or even Pub/Sub ● Usage of Redis to store Ruby objects ● Why would you want to do that?
  • 3. Quick Redis 101 - Datatypes ● Keys are strings, no need to quote ● Strings ● Integers (not really- INCR is a string operation) ● Lists ● Sets ● Sorted Sets (sets with a score) ● http://redis.oi (interactive terminal; website written in cuba.io, incidentally)
  • 4. Let's talk Ruby ● Ruby has strings, hashes, arrays.. ● And hashes are many times used as data storage for Ruby objects.. ● Wouldn't it be nice to use Redis to persist Ruby objects?
  • 5. Redis-rb ● Download and install redis http://redis.io/download ● Install ruby gem $ gem install redis ● Connection require 'redis' db = Redis.new
  • 6. Ruby Serialization * ● Suppose a simple hash movie = Hash[ :name, 'Top Gun', :genre, 'Action' ] ● Might be represented in redis as: db.hmset 'movie:1', 'name', 'Top Gun', 'genre', 'Action'
  • 7. Auto-increment ID ● Notice incrementing in the key name db.hmset 'movie:1', 'name', 'Top Gun', 'genre', 'Action' ● Create tooling to track id's, we can use INCR def get_pk(item, db) pk = db.incr "#{item}:pk" "#{item}:#{pk}" end db.hmset get_pk('movies', db), 'name', 'Top Gun', ...
  • 8. References ● A reference, like in AR 'belongs_to' ● Could be implemented similarly: db.hmset 'character:1', 'movie_id', 'movie:1'
  • 9. Has Many ● Embed as one of the keys # Make a few jets db.hmset 'jet:1', 'manufacturer', 'Grumman', 'model', 'F-14' db.hmset 'jet:2', 'manufacturer', 'Northrop', 'model', 'F-5' # Make our movie db.hmset 'movie:1', 'jets', %w(jet:1 jet:2).to_json
  • 10. Has Many (set) ● But that's not really “redisy” ● How about conceiving a new key name and creating a set? # Make a few jets db.hmset 'jet:1', 'manufacturer', 'Grumman', 'model', 'F-14' db.hmset 'jet:2', 'manufacturer', 'Northrop', 'model', 'F-5' # Make our movie db.hmset 'movie:1', 'name', 'Top Gun', 'genre', 'Action' # Add to a key to represent the set of jets db.sadd 'movie:1:jets', 'jet:1' db.sadd 'movie:1:jets', 'jet:2'
  • 11. Find / Indexing ● Finding items, need an index. ● Indexes could be sets with prescribed keys. # Create a few movies db.hmset 'movie:1', 'name', 'Top Gun', 'genre', 'Action' db.hmset 'movie:2', 'name', 'Top Gun', 'genre', 'Action' db.hmset 'movie:3', 'name', 'Airplane', 'genre', 'Comedy' # Create an index on 'genre' db.sadd 'movie:index:genre:Action', 'movie:1' db.sadd 'movie:index:genre:Action', 'movie:2' db.sadd 'movie:index:genre:Comedy', 'movie:3'
  • 13. We need a Key Strategy ● Among other things...
  • 14. Nest ● Very simple convention <klass.underscore>:<identifier> movie:1 jet:10 character:iceman ● https://github.com/soveran/nest/blob/master/lib/nest.rb
  • 15. We need tooling to manage relationships ● Nest gives nice convention for key, but what about sets, lists, references, indexes, collections, validation, callbacks, etc... ● Enter Ohm ● https://github.com/soveran/ohm
  • 16. Ohm: Redis-Ruby Object Hash Mapper ● Ohm models for movies, characters and jets. (see code)
  • 18. Devops - AOF ● AOF is a newish strategy for managing data. ● Configuration (redis.conf): appendonly yes appendfilename appendonly.aof ● Process to save is: ● issue 'BGREWRITEAOF' ● loop until complete ● Process to load is: ● stop redis ● copy AOF file to prescribed location (redis.conf) ● loop until loading is complete
  • 19. Devops – AOF save %x{ echo "BGREWRITEAOF" | redis-cli } loop do sleep 1 puts " * Waiting for aof to save..." save_status = %x{ echo "INFO" | redis-cli | grep bgrewriteaof_in_progress }[/:([0-9])/,1] break if save_status == "0" end puts "DONE!"
  • 20. Devops – AOF load loop do sleep 1 puts " * Waiting for aof to load..." load_status = %x{ echo "INFO" | redis-cli | grep loading }[/:([0-9])/,1] break if load_status == "0" end puts "DONE"
  • 21. Devops - Sockets ● Faster, no TCP overhead ● Configuration (redis.conf) # port 6379 unixsocket /tmp/redis.sock ● Redis-cli $ redis-cli -s /tmp/redis.sock ● Redis.rb Redis.new(:path => '/tmp/redis.sock')
  • 22. Ohm::Contrib https://github.com/sinefunc/ohm-contrib ● Ohm::Boundaries ● Ohm::Callbacks ● Ohm::Timestamping ● Ohm::ToHash ● Ohm::WebValidations ● Ohm::NumberValidations ● Ohm::ExtraValidations ● Ohm::Typecast ● Ohm::Locking
  • 23. Ohm::Contrib is hacky ruby-1.9.2-p180 :016 > os = Ohm::Types::String.new "key"; s = "key" ruby-1.9.2-p180 :018 > os == s => true ruby-1.9.2-p180 :019 > os === s => true ruby-1.9.2-p180 :020 > hsh = { os => 'foo' } => {"key"=>"foo"} ruby-1.9.2-p180 :021 > hsh[os] => "foo" ruby-1.9.2-p180 :022 > hsh[s] => nil
  • 24. Hacks - Overriding redis_id require 'ohm' class Ohm class Model # initialize: added ability to pass redis_id and have it define the actual Ohm ID. (new? is broken in Ohm, BTW) alias_method :initialize_without_redis_id, :initialize def initialize_with_redis_id(args={}) @redis_id = args.delete(:redis_id) initialize_without_redis_id(args) end alias_method :initialize, :initialize_with_redis_id def initialize_id @id ||= (@redis_id || self.class.key[:id].incr.to_s) end private :initialize_id end
  • 25. Hacks – Adding list/set by id ● Default to have the Ohm saved, use << ● We wanted to pass in id, since we prescribed them anyway. class List def push_id(model_id) key.rpush(model_id) end end class Set def push_id(model_id) key.sadd(model_id) end end