SlideShare ist ein Scribd-Unternehmen logo
1 von 70
Wer bin ich?



     Norman Soetbeer

  Twitter: @TheBattleRattle

Game Developer @ InnoGames
Redis


                                      LevelDB
                       Key-Value
                        Storages
                                    MemcacheDB
                       Document
                        Storages
              NoSQL                     …
                         Graph-
Datenbanken
                      Datenbanken
               SQL
                          …
In-Memory
 alle Daten immer im RAM
 sehr schnell
   – 100.000 Schreibzugriffe / Sekunde
   – 80.000 Lesezugriffe / Sekunde

Single-Threaded
 non-blocking I/O
 Ausnahme: Threads für Festplattenzugriffe
Key              Value
player:1:name    SuperPimp99
player:1:score   12345
player:2:name    MegaBasher12
player:2:score   45678
town:27:name     Troja
…                …
Key                            Value
player:1:name                  SuperPimp99
player:1:score                 12345
player:2:name                  MegaBasher12
player:2:score                 45678
town:27:name                   Troja
…                              …



 beliebige Zeichenkette (binary-safe)
 keine Maximallänge bekannt
 ABER: längere Strings = mehr Speicher + schlechtere Performance
Key              Value
player:1:name    SuperPimp99
player:1:score   12345
player:2:name    MegaBasher12
player:2:score   45678
town:27:name     Troja
…                …



                  verschiedene Datentypen
Allgemeine Befehle
   EXPIRE / EXPIREAT: Lifetime für einen Eintrag setzen
   TTL: verbleibende Lifetime bestimmen
   PERSIST: entfernt Ablaufzeit
   EXISTS: Existenz eines Eintrags prüfen
   TYPE: Datentyp eines Eintrags bestimmen
String
          Key                       Value
          player:1:name             SuperPimp99
          player:1:score            12345
          player:2:name             MegaBasher12
          player:2:score            45678
          town:27:name              Troja
          …                         …

   beliebige Zeichenkette (binary-safe)
   max. 512 MB
String
         Key                 Value
         player:1:name       SuperPimp99
         player:1:score      12345
         player:2:name       MegaBasher12
         player:2:score      45678
         town:27:name        Troja
         …                   …

Wert lesen

      Schlüsselname
GET player:1:name
"SuperPimp99"
String
         Key                        Value
         player:1:name              SuperPimp99 Klaus
         player:1:score             12345
         player:2:name              MegaBasher12
         player:2:score             45678
         town:27:name               Troja
         …                          …

Wert schreiben

      Schlüsselname       Wert
SET player:1:name Klaus
OK
String
         Key                        Value
         player:1:name              Klaus
         player:1:score             12345
         player:2:name              MegaBasher12
         player:2:score             45678
         town:27:name               Troja
         …                          …

Wert schreiben, falls noch nicht vorhanden

        Schlüsselname     Wert
SETNX player:1:name Hans
0
String
        Key                     Value
        player:1:name           Klaus
        player:1:score          12345
        player:2:name           MegaBasher12
        player:2:score          45678
        town:27:name            Troja
        …                       …

Länge eines Strings bestimmen

         Schlüsselname
STRLEN player:2:name
12
String
        Key                     Value
        player:1:name           Klaus Meier
        player:1:score          12345
        player:2:name           MegaBasher12
        player:2:score          45678
        town:27:name            Troja
        …                       …

String anhängen

        Schlüsselname    Wert
APPEND player:1:name " Meier"
11
String
         Key                                Value
         player:1:name                      Klaus Meier
         player:1:score                     12345
         player:2:name                      MegaBasher12
         player:2:score                     45678
         town:27:name                       Troja
         …                                  …

Teil eines Strings auslesen / schreiben

               Schlüsselname   End-Offset
GETRANGE player:1:name 1 4
"laus"              Start-Offset
String
         Key                         Value
         player:1:name               Klaus Meier
         player:1:score              12345
         player:2:name              MegaBasher12
                          01001011 01101100 …
         player:2:score             45678
         town:27:name                Troja
         …                           …

Einzelne Bits setzen / auslesen

         Schlüsselname Offset
GETBIT player:1:name 6
1
String
        Key                 Value
        player:1:name       Klaus Meier
        player:1:score      12345 12346
        player:2:name       MegaBasher12
        player:2:score      45678
        town:27:name        Troja
        …                   …

Inkrement / Dekrement

      Schlüsselname
INCR player:1:score
12346
String
Anwendungsbeispiele
 Speicherung "einfacher" Werte
 Flags (Key vorhanden / nicht vorhanden)
 Zähler
 Sequenz / ID-Generator
Liste
          Key                Value
          …                  …

          player:1:actions    account:login     build:main   recruit:sword   account:logout



          …                  …




   Sequenz von Elementen (Strings) in definierter Reihenfolge
   max. 232-1 Elemente pro Liste
Liste
       Key                Value
       …                  …
           LPUSH                                                                                         RPUSH
       player:1:actions    account:login   build:main   recruit:sword   account:logout   account:login




       …                  …




Elemente anhängen

        Schlüsselname       Wert
RPUSH player:1:actions account:login
5
Liste
        Key                   Value
        …                     …

        player:1:actions          build:main    recruit:sword   account:logout   account:login



        …      LPOP           …                                                                  RPOP

              account:login




Elemente entfernen

        Schlüsselname
LPOP player:1:actions
"account:login"
Liste
        Key                Value
        …                  …

        player:1:actions       build:main    recruit:sword   account:logout   account:login



        …                  …




Länge der Liste bestimmen

        Schlüsselname
LLEN player:1:actions
4
Liste
         Key                Value
         …                  …

         player:1:actions       build:main    recruit:sword   account:logout   account:login


                                    0              1               2                3
         …                  …      (-4)           (-3)            (-2)             (-1)




Element an beliebiger Position auslesen

         Schlüsselname Offset
LINDEX player:1:actions 1
"recruit:sword"
Liste
         Key                Value
         …                  …

         player:1:actions       build:main    recruit:sword   account:logout   account:login


                                    0              1               2                3
         …                  …      (-4)           (-3)            (-2)             (-1)




Sequenz auslesen
          Schlüsselname    End-Offset
LRANGE player:1:actions 1 3
"recruit:sword"         Start-Offset
"account:logout"
"account:login"
Liste
         Key                Value
         …                  …       0              1                 2               3
                                   (-4)           (-3)              (-2)            (-1)
                                                                                                vorher
         player:1:actions       build:main    recruit:sword    account:logout   account:login




         player:1:actions    recruit:sword    account:logout

                                                                                                nachher
                                    0              1
         …                  …      (-2)           (-1)
Liste kappen

         Schlüsselname    End-Offset
LTRIM player:1:actions 1 2
OK                     Start-Offset
Liste
Anwendungsbeispiele
 Queue (RPUSH + LPOP)
 Stack (RPUSH + RPOP)
   Verlauf (letzte Aktionen, letzte Beiträge, Chat-Nachrichten)
Hash
         Key           Value
         …             …

                        name             SuperPimp99
         player:1       level            12
                        experience       345

         …             …


   assoziative Abbildung: String => String
   max. 232-1 Schlüssel-Wert-Paare pro Hash
Hash
Befehle ähnlich wie bei Strings:
 Attribut(e) schreiben/lesen (HSET, HGET, HMSET, HMGET)
 alle Attribute lesen (HGETALL)
 Attribut(e) löschen (HDEL)
 Anzahl der Attribute bestimmen (HLEN)
 Inkrementieren (HINCRBY)

Anwendungsbeispiele:
 Objekt-Speicher / Objekt-Cache
Menge (Set)
         Key             Value
         …               …

         active_users:               34     918
         2012-08-17              7                713
                                      291

         …               …


   ungeordnete Sammlung von Elementen (Strings)
   jedes Element höchstens einmal in Set vorhanden
   max. 232-1 Elemente pro Set
Menge (Set)
        Key               Value
        …                 …

        active_users:                   34     918
        2012-08-17                                         291
                                  7                  713
                                         291

        …                 …


Element(e) hinzufügen

              Schlüsselname           Wert
SADD active_users:2012-08-17 123
1
Menge (Set)
        Key               Value
        …                 …

        active_users:                   34     918
        2012-08-17                                         291
                                  7                  713
                                         291

        …                 …


Element(e) entfernen

              Schlüsselname           Wert
SREM active_users:2012-08-17 291
1
Menge (Set)
        Key              Value
        …                …

        active_users:                34    918
        2012-08-17                                      291
                                 7                713


        …                …


Überprüfen, ob Element in Set enthalten

                    Schlüsselname          Wert
SISMEMBER active_users:2012-08-17 something
0
Menge (Set)
        Key             Value
        …               …

        active_users:               34      918
        2012-08-17                                      291
                                7                 713


        …               …


Anzahl der Elemente bestimmen

              Schlüsselname
SCARD active_users:2012-08-17
5
Menge (Set)
        Key                Value
        …                  …

        active_users:                   34   918
        2012-08-17                                       291
                                   7               713


        …                  …


Zufälliges Element bestimmen

                        Schlüsselname
SRANDMEMBER active_users:2012-08-17
"918"
Menge (Set)
Mengenoperationen:
 Vereinigung (SUNION, SUNIONSTORE)
 Durchschnitt (SINTER, SINTERSTORE)
 Differenz (SDIFF, SDIFFSTORE)

Anwendungsbeispiele:
 "Unique"-Zähler
 Mitgliedschaften (Stamm, Allianz, Freundesliste)
 Flags für Spieler (Wert vorhanden / nicht vorhanden)
Sortierte Menge (Sorted Set)
         Key               Value
         …                 …
                               Score          Wert (String)
                            123        SuperPimp99
         ranking:players    456        UltraBasher14
                            999        PowerPumper
                            1337       GamerGirl2012

         …                 …
   wie Set: jedes Element höchstens einmal vorhanden
   aber definierte Reihenfolge durch SCORE (double)
   stets aufsteigend sortiert
   max. 232-1 Elemente pro Sorted Set
Sortierte Menge (Sorted Set)
        Key               Value
        …                 …
                           123    SuperPimp99
                           456    UltraBasher14
        ranking:players
                           789    MegaFighter
                           999    PowerPumper
                           1337   GamerGirl2012

        …                 …
Element(e) hinzufügen / updaten

       Schlüsselname      Score   Wert
ZADD ranking:players 789 MegaFighter
1
Sortierte Menge (Sorted Set)
        Key               Value
        …                 …

                           123           SuperPimp99
        ranking:players    456           UltraBasher14
                           789           MegaFighter
                                                         999   PowerPumper
                           1337          GamerGirl2012

        …                 …
Element(e) entfernen

       Schlüsselname              Wert
ZREM ranking:players PowerPumper
1
Sortierte Menge (Sorted Set)
        Key               Value
        …                 …

                           123    SuperPimp99
        ranking:players    456    UltraBasher14
                           789    MegaFighter
                           1337   GamerGirl2012

        …                 …
Anzahl der Elemente ermitteln

         Schlüsselname
ZCARD ranking:players
4
Sortierte Menge (Sorted Set)
        Key              Value
        …                …

                        0 123       SuperPimp99
        ranking:players 1 456       UltraBasher14
                        2 789       MegaFighter
                        3 1337      GamerGirl2012

        …                …
Rang eines Elements bestimmen
                                                    Achtung!
        Schlüsselname            Wert                aufsteigende Reihenfolge
ZRANK ranking:players GamerGirl2012                  Rang beginnt bei 0
3
Sortierte Menge (Sorted Set)
        Key               Value
        …                 …

                         3 123    SuperPimp99
        ranking:players 2 456     UltraBasher14
                        1 789     MegaFighter
                         0 1337   GamerGirl2012

        …                 …
Rang eines Elements bestimmen (absteigend)

              Schlüsselname       Wert
ZREVRANK ranking:players GamerGirl2012
0
Sortierte Menge (Sorted Set)
         Key              Value
         …                …

                         3 123          SuperPimp99
         ranking:players 2 456          UltraBasher14
                         1 789          MegaFighter
                         0 1337         GamerGirl2012

         …                …
Bereich auslesen (absteigend)
               Schlüsselname     End-Offset
ZREVRANGE ranking:players 0 2
"GamerGirl2012"       Start-Offset
"MegaFighter"
"UltraBasher14"
Sortierte Menge (Sorted Set)
Anwendungsbeispiele:
 Live-Ranking
 sortierte Mitgliedschaften (Allianzmitglieder nach Beitrittsdatum
  sortiert)
 Index für Hash-Attribute
    Hashes für Spieler-Objekte
     "player:2": {"name": "Basher", "level": "50"}
    Sorted Set als Index für "level"-Attribut
     "player:levels": {score: 50, value: "2"}
    Abfrage: IDs aller Spieler mit Level zwischen 50 und 100, absteigend
     sortiert nach Level
        SQL: SELECT id FROM players WHERE level BETWEEN 50 AND 100 ORDER
         BY level DESC
        Redis: ZREVRANGEBYSCORE player:levels 50 100
Bisher




Problem: viele Round-Trips = langsam
Lösung: Pipeline




   Änderung der Abfolge von Senden u. Empfangen
       S-E-S-E-S-E vs. S-S-S-E-E-E
   Implementierung clientseitig
   Befehlsausführung nicht atomar!
Beispiel: PHP + Predis
require 'predis/autoload.php';

$config = array(                                            lokal       entfernt (LAN)
    'host' => 'localhost',                  ohne Pipeline   1,86 Sek.   5,13 Sek.
    'port' => 6379,
    'database' => 0,                        mit Pipeline    1,60 Sek.   1,48 Sek.
);

$redis = new PredisClient($config);

// ohne Pipeline
$start = microtime(true);
for ($i=0; $i<10000; $i++) {
    $redis->set('key' . $i, $i);
}
printf("execution took %.2f secondsn", microtime(true) - $start);

// mit Pipeline
$start = microtime(true);
$redis->pipeline(function($pipe) {
    for ($i=0; $i<10000; $i++) {
        $pipe->set('key' . $i, $i);
    }
});
printf("execution took %.2f secondsn", microtime(true) - $start);
Transaktionen
Abfolge:                               Beispiel:
 Transaktion starten (MULTI)          MULTI
   Befehle senden                     OK
       werden auf Server gesammelt    SET first_key "test 1"
       Antwort ist immer "QUEUED"
        (Ausnahme: Syntaxfehler)
                                       QUEUED
   Transaktion ausführen (EXEC)       SET second_key "test 2"
   oder Transaktion abbrechen         QUEUED
    (DISCARD)                          SET third_key "test 3"
                                       QUEUED
                                       EXEC
                                       OK
                                       OK
                                       OK
Transaktionen
Eigenschaften:
 Ausführung atomar
 "alles oder nichts"
      bei DISCARD oder Verbindungsabbruch wird nichts ausgeführt
      mit EXEC wird alles ausgeführt
      Achtung: kein Abbruch/Rollback bei Fehlern!
Scripting
   Unterstützung ab Redis 2.6
   analog zu Stored Procedures
   Sprache: LUA
   Scriptausführung:
     "on the fly":
                                  LUA-Script                1. Parameter
        EVAL "return redis.call('set', KEYS[1], 'bar')" 1 foo
        OK                                         Parameter-Anzahl
     speichern und später ausführen:
                                               LUA-Script

        SCRIPT LOAD "return redis.call('set', KEYS[1], 'bar')"
        "f8211e1772142e888d2b3eef9fd3894eb1b06b17"
                               SHA1-Hash des Scripts         1. Parameter
        EVALSHA f8211e1772142e888d2b3eef9fd3894eb1b06b17 1 foo
        OK                                          Parameter-Anzahl
   atomar => langsames Script kann Server ausbremsen!
Publish/Subscribe
Publisher:
 verschickt Nachrichten an Kanäle

Subscriber:
 lauscht auf einem oder mehreren Kanälen
 empfängt Nachrichten des Publishers
Publish/Subscribe
                                                           S1
     P1



   P2                                      logs.critical    S2



     P3                                                    S3


Channel abonnieren
              Channel-Name
SUBSCRIBE "logs.critical"
1
Publish/Subscribe
                                                           S1
     P1



    P2                                     logs.critical    S2



     P3                                                    S3


Channel mit Platzhaltern abonnieren
              Muster     Muster
PSUBSCRIBE "logs.*" "chat.*"
1
Publish/Subscribe
                                                                 S1
      P1

 "something happened"

    P2                                           logs.critical    S2



      P3                                                         S3


Nachricht senden
                  Channel            Nachricht
Publish "logs.warning" "something happened"
2
Publish/Subscribe
                                                                              S1
             P1

"something critical happened"                             "something critical happened"

           P2                                                 logs.critical    S2



             P3                                                               S3


      Nachricht senden
                          Channel                 Nachricht
      Publish "logs.critical" "something critical happened"
      3
Persistenz
RDB - Dump
 "point-in-time snapshot"
 wird erstellt, wenn X Update-Operationen in Y Sekunden erfolgt
 Standardeinstellungen:
     save 900 1 Dump, wenn mind. 1 Update in 15 Minuten
     save 300 10 Dump, wenn mind. 10 Updates in 5 Minuten
     save 60 10000 Dump, wenn mind. 10.000 Updates in 1 Minute


   Vorteile:
      Einspielen des Backups relativ schnell


   Nachteile:
      Datenverlust kann groß sein
      Speichervorgang aufwendig (große Datenmenge)
Persistenz
AOF (append-only-file)
 jeder einzelne Befehl geloggt
 Wiedereinspielen der Daten durch Ausführung dieser Befehle
 Schreib-Intervall konfigurierbar:
        OS entscheidet (schnell)
        jedes Query (langsam, aber sicher)
        jede Sekunde (Kompromiss)


   Vorteile:
      relativ sicher, Datenverlust gering


   Nachteile:
      Einspielen des Backups langsam
Persistenz
RDB vs. AOF
 keine Lösung besser oder schlechter als die andere
=> Entscheidung: Wie kritisch ist ein Datenverlust?
 beides auch in Kombination nutzbar
Skalierbarkeit
Master-Slave-Replikation
 1 Master, mehrere Slaves
 Slaves können selbst weitere Slaves besitzen
 Synchronisierung: Master -> Slave
       Slaves können Schreiboperationen ausführen, aber nicht mit Master
        synchronisieren!
   einfache Handhabung:
       Server als Slave starten: redis-server --slaveof 127.0.0.1 6379
       automatische Synchronisierung
       Auto-Reconnect bei Verbindungsabbruch
Skalierbarkeit
Redis Cluster (noch in Alpha-Phase!)
 bis zu 4096 Knoten
 Ziel: lineare Skalierbarkeit
 Schlüssel werden auf Knoten verteilt ("Consistent Hashing")
 Redundanz-Faktor konfigurierbar ("Live-Backup")
       Jeder Schlüssel existiert auf 1 Master + N Slaves (Slaves = read-only)
   Fehlertoleranz:
       Knoten "pingen" sich gegenseitig
       bei Timeout wird Knoten als "nicht verfügbar" markiert (alle Knoten des
        Clusters werden informiert)
       Wenn Knoten wieder online ist, wird er "runtergefahren" (mögliche
        Dateninkonsistenz)
   http://redis.io

   http://www.cafebabe.me/2011/05/redis-pipelines-and-
    transactions.html
Vielen Dank
für die Aufmerksamkeit!

       Fragen?

Weitere ähnliche Inhalte

Empfohlen

PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...DevGAMM Conference
 

Empfohlen (20)

Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 

Redis (PHP Unconference 2012, deutsch)

  • 1.
  • 2. Wer bin ich? Norman Soetbeer Twitter: @TheBattleRattle Game Developer @ InnoGames
  • 3.
  • 4.
  • 5.
  • 6. Redis LevelDB Key-Value Storages MemcacheDB Document Storages NoSQL … Graph- Datenbanken Datenbanken SQL …
  • 7. In-Memory  alle Daten immer im RAM  sehr schnell – 100.000 Schreibzugriffe / Sekunde – 80.000 Lesezugriffe / Sekunde Single-Threaded  non-blocking I/O  Ausnahme: Threads für Festplattenzugriffe
  • 8.
  • 9.
  • 10. Key Value player:1:name SuperPimp99 player:1:score 12345 player:2:name MegaBasher12 player:2:score 45678 town:27:name Troja … …
  • 11. Key Value player:1:name SuperPimp99 player:1:score 12345 player:2:name MegaBasher12 player:2:score 45678 town:27:name Troja … …  beliebige Zeichenkette (binary-safe)  keine Maximallänge bekannt  ABER: längere Strings = mehr Speicher + schlechtere Performance
  • 12. Key Value player:1:name SuperPimp99 player:1:score 12345 player:2:name MegaBasher12 player:2:score 45678 town:27:name Troja … …  verschiedene Datentypen
  • 13. Allgemeine Befehle  EXPIRE / EXPIREAT: Lifetime für einen Eintrag setzen  TTL: verbleibende Lifetime bestimmen  PERSIST: entfernt Ablaufzeit  EXISTS: Existenz eines Eintrags prüfen  TYPE: Datentyp eines Eintrags bestimmen
  • 14. String Key Value player:1:name SuperPimp99 player:1:score 12345 player:2:name MegaBasher12 player:2:score 45678 town:27:name Troja … …  beliebige Zeichenkette (binary-safe)  max. 512 MB
  • 15. String Key Value player:1:name SuperPimp99 player:1:score 12345 player:2:name MegaBasher12 player:2:score 45678 town:27:name Troja … … Wert lesen Schlüsselname GET player:1:name "SuperPimp99"
  • 16. String Key Value player:1:name SuperPimp99 Klaus player:1:score 12345 player:2:name MegaBasher12 player:2:score 45678 town:27:name Troja … … Wert schreiben Schlüsselname Wert SET player:1:name Klaus OK
  • 17. String Key Value player:1:name Klaus player:1:score 12345 player:2:name MegaBasher12 player:2:score 45678 town:27:name Troja … … Wert schreiben, falls noch nicht vorhanden Schlüsselname Wert SETNX player:1:name Hans 0
  • 18. String Key Value player:1:name Klaus player:1:score 12345 player:2:name MegaBasher12 player:2:score 45678 town:27:name Troja … … Länge eines Strings bestimmen Schlüsselname STRLEN player:2:name 12
  • 19. String Key Value player:1:name Klaus Meier player:1:score 12345 player:2:name MegaBasher12 player:2:score 45678 town:27:name Troja … … String anhängen Schlüsselname Wert APPEND player:1:name " Meier" 11
  • 20. String Key Value player:1:name Klaus Meier player:1:score 12345 player:2:name MegaBasher12 player:2:score 45678 town:27:name Troja … … Teil eines Strings auslesen / schreiben Schlüsselname End-Offset GETRANGE player:1:name 1 4 "laus" Start-Offset
  • 21. String Key Value player:1:name Klaus Meier player:1:score 12345 player:2:name MegaBasher12 01001011 01101100 … player:2:score 45678 town:27:name Troja … … Einzelne Bits setzen / auslesen Schlüsselname Offset GETBIT player:1:name 6 1
  • 22. String Key Value player:1:name Klaus Meier player:1:score 12345 12346 player:2:name MegaBasher12 player:2:score 45678 town:27:name Troja … … Inkrement / Dekrement Schlüsselname INCR player:1:score 12346
  • 23. String Anwendungsbeispiele  Speicherung "einfacher" Werte  Flags (Key vorhanden / nicht vorhanden)  Zähler  Sequenz / ID-Generator
  • 24. Liste Key Value … … player:1:actions account:login build:main recruit:sword account:logout … …  Sequenz von Elementen (Strings) in definierter Reihenfolge  max. 232-1 Elemente pro Liste
  • 25. Liste Key Value … … LPUSH RPUSH player:1:actions account:login build:main recruit:sword account:logout account:login … … Elemente anhängen Schlüsselname Wert RPUSH player:1:actions account:login 5
  • 26. Liste Key Value … … player:1:actions build:main recruit:sword account:logout account:login … LPOP … RPOP account:login Elemente entfernen Schlüsselname LPOP player:1:actions "account:login"
  • 27. Liste Key Value … … player:1:actions build:main recruit:sword account:logout account:login … … Länge der Liste bestimmen Schlüsselname LLEN player:1:actions 4
  • 28. Liste Key Value … … player:1:actions build:main recruit:sword account:logout account:login 0 1 2 3 … … (-4) (-3) (-2) (-1) Element an beliebiger Position auslesen Schlüsselname Offset LINDEX player:1:actions 1 "recruit:sword"
  • 29. Liste Key Value … … player:1:actions build:main recruit:sword account:logout account:login 0 1 2 3 … … (-4) (-3) (-2) (-1) Sequenz auslesen Schlüsselname End-Offset LRANGE player:1:actions 1 3 "recruit:sword" Start-Offset "account:logout" "account:login"
  • 30. Liste Key Value … … 0 1 2 3 (-4) (-3) (-2) (-1) vorher player:1:actions build:main recruit:sword account:logout account:login player:1:actions recruit:sword account:logout nachher 0 1 … … (-2) (-1) Liste kappen Schlüsselname End-Offset LTRIM player:1:actions 1 2 OK Start-Offset
  • 31. Liste Anwendungsbeispiele  Queue (RPUSH + LPOP)  Stack (RPUSH + RPOP)  Verlauf (letzte Aktionen, letzte Beiträge, Chat-Nachrichten)
  • 32. Hash Key Value … … name SuperPimp99 player:1 level 12 experience 345 … …  assoziative Abbildung: String => String  max. 232-1 Schlüssel-Wert-Paare pro Hash
  • 33. Hash Befehle ähnlich wie bei Strings:  Attribut(e) schreiben/lesen (HSET, HGET, HMSET, HMGET)  alle Attribute lesen (HGETALL)  Attribut(e) löschen (HDEL)  Anzahl der Attribute bestimmen (HLEN)  Inkrementieren (HINCRBY) Anwendungsbeispiele:  Objekt-Speicher / Objekt-Cache
  • 34. Menge (Set) Key Value … … active_users: 34 918 2012-08-17 7 713 291 … …  ungeordnete Sammlung von Elementen (Strings)  jedes Element höchstens einmal in Set vorhanden  max. 232-1 Elemente pro Set
  • 35. Menge (Set) Key Value … … active_users: 34 918 2012-08-17 291 7 713 291 … … Element(e) hinzufügen Schlüsselname Wert SADD active_users:2012-08-17 123 1
  • 36. Menge (Set) Key Value … … active_users: 34 918 2012-08-17 291 7 713 291 … … Element(e) entfernen Schlüsselname Wert SREM active_users:2012-08-17 291 1
  • 37. Menge (Set) Key Value … … active_users: 34 918 2012-08-17 291 7 713 … … Überprüfen, ob Element in Set enthalten Schlüsselname Wert SISMEMBER active_users:2012-08-17 something 0
  • 38. Menge (Set) Key Value … … active_users: 34 918 2012-08-17 291 7 713 … … Anzahl der Elemente bestimmen Schlüsselname SCARD active_users:2012-08-17 5
  • 39. Menge (Set) Key Value … … active_users: 34 918 2012-08-17 291 7 713 … … Zufälliges Element bestimmen Schlüsselname SRANDMEMBER active_users:2012-08-17 "918"
  • 40. Menge (Set) Mengenoperationen:  Vereinigung (SUNION, SUNIONSTORE)  Durchschnitt (SINTER, SINTERSTORE)  Differenz (SDIFF, SDIFFSTORE) Anwendungsbeispiele:  "Unique"-Zähler  Mitgliedschaften (Stamm, Allianz, Freundesliste)  Flags für Spieler (Wert vorhanden / nicht vorhanden)
  • 41. Sortierte Menge (Sorted Set) Key Value … … Score Wert (String) 123 SuperPimp99 ranking:players 456 UltraBasher14 999 PowerPumper 1337 GamerGirl2012 … …  wie Set: jedes Element höchstens einmal vorhanden  aber definierte Reihenfolge durch SCORE (double)  stets aufsteigend sortiert  max. 232-1 Elemente pro Sorted Set
  • 42. Sortierte Menge (Sorted Set) Key Value … … 123 SuperPimp99 456 UltraBasher14 ranking:players 789 MegaFighter 999 PowerPumper 1337 GamerGirl2012 … … Element(e) hinzufügen / updaten Schlüsselname Score Wert ZADD ranking:players 789 MegaFighter 1
  • 43. Sortierte Menge (Sorted Set) Key Value … … 123 SuperPimp99 ranking:players 456 UltraBasher14 789 MegaFighter 999 PowerPumper 1337 GamerGirl2012 … … Element(e) entfernen Schlüsselname Wert ZREM ranking:players PowerPumper 1
  • 44. Sortierte Menge (Sorted Set) Key Value … … 123 SuperPimp99 ranking:players 456 UltraBasher14 789 MegaFighter 1337 GamerGirl2012 … … Anzahl der Elemente ermitteln Schlüsselname ZCARD ranking:players 4
  • 45. Sortierte Menge (Sorted Set) Key Value … … 0 123 SuperPimp99 ranking:players 1 456 UltraBasher14 2 789 MegaFighter 3 1337 GamerGirl2012 … … Rang eines Elements bestimmen Achtung! Schlüsselname Wert  aufsteigende Reihenfolge ZRANK ranking:players GamerGirl2012  Rang beginnt bei 0 3
  • 46. Sortierte Menge (Sorted Set) Key Value … … 3 123 SuperPimp99 ranking:players 2 456 UltraBasher14 1 789 MegaFighter 0 1337 GamerGirl2012 … … Rang eines Elements bestimmen (absteigend) Schlüsselname Wert ZREVRANK ranking:players GamerGirl2012 0
  • 47. Sortierte Menge (Sorted Set) Key Value … … 3 123 SuperPimp99 ranking:players 2 456 UltraBasher14 1 789 MegaFighter 0 1337 GamerGirl2012 … … Bereich auslesen (absteigend) Schlüsselname End-Offset ZREVRANGE ranking:players 0 2 "GamerGirl2012" Start-Offset "MegaFighter" "UltraBasher14"
  • 48. Sortierte Menge (Sorted Set) Anwendungsbeispiele:  Live-Ranking  sortierte Mitgliedschaften (Allianzmitglieder nach Beitrittsdatum sortiert)  Index für Hash-Attribute  Hashes für Spieler-Objekte "player:2": {"name": "Basher", "level": "50"}  Sorted Set als Index für "level"-Attribut "player:levels": {score: 50, value: "2"}  Abfrage: IDs aller Spieler mit Level zwischen 50 und 100, absteigend sortiert nach Level  SQL: SELECT id FROM players WHERE level BETWEEN 50 AND 100 ORDER BY level DESC  Redis: ZREVRANGEBYSCORE player:levels 50 100
  • 49.
  • 50.
  • 52. Lösung: Pipeline  Änderung der Abfolge von Senden u. Empfangen  S-E-S-E-S-E vs. S-S-S-E-E-E  Implementierung clientseitig  Befehlsausführung nicht atomar!
  • 53. Beispiel: PHP + Predis require 'predis/autoload.php'; $config = array( lokal entfernt (LAN) 'host' => 'localhost', ohne Pipeline 1,86 Sek. 5,13 Sek. 'port' => 6379, 'database' => 0, mit Pipeline 1,60 Sek. 1,48 Sek. ); $redis = new PredisClient($config); // ohne Pipeline $start = microtime(true); for ($i=0; $i<10000; $i++) { $redis->set('key' . $i, $i); } printf("execution took %.2f secondsn", microtime(true) - $start); // mit Pipeline $start = microtime(true); $redis->pipeline(function($pipe) { for ($i=0; $i<10000; $i++) { $pipe->set('key' . $i, $i); } }); printf("execution took %.2f secondsn", microtime(true) - $start);
  • 54. Transaktionen Abfolge: Beispiel:  Transaktion starten (MULTI) MULTI  Befehle senden OK  werden auf Server gesammelt SET first_key "test 1"  Antwort ist immer "QUEUED" (Ausnahme: Syntaxfehler) QUEUED  Transaktion ausführen (EXEC) SET second_key "test 2"  oder Transaktion abbrechen QUEUED (DISCARD) SET third_key "test 3" QUEUED EXEC OK OK OK
  • 55. Transaktionen Eigenschaften:  Ausführung atomar  "alles oder nichts"  bei DISCARD oder Verbindungsabbruch wird nichts ausgeführt  mit EXEC wird alles ausgeführt  Achtung: kein Abbruch/Rollback bei Fehlern!
  • 56. Scripting  Unterstützung ab Redis 2.6  analog zu Stored Procedures  Sprache: LUA  Scriptausführung:  "on the fly": LUA-Script 1. Parameter EVAL "return redis.call('set', KEYS[1], 'bar')" 1 foo OK Parameter-Anzahl  speichern und später ausführen: LUA-Script SCRIPT LOAD "return redis.call('set', KEYS[1], 'bar')" "f8211e1772142e888d2b3eef9fd3894eb1b06b17" SHA1-Hash des Scripts 1. Parameter EVALSHA f8211e1772142e888d2b3eef9fd3894eb1b06b17 1 foo OK Parameter-Anzahl  atomar => langsames Script kann Server ausbremsen!
  • 57.
  • 58.
  • 59. Publish/Subscribe Publisher:  verschickt Nachrichten an Kanäle Subscriber:  lauscht auf einem oder mehreren Kanälen  empfängt Nachrichten des Publishers
  • 60. Publish/Subscribe S1 P1 P2 logs.critical S2 P3 S3 Channel abonnieren Channel-Name SUBSCRIBE "logs.critical" 1
  • 61. Publish/Subscribe S1 P1 P2 logs.critical S2 P3 S3 Channel mit Platzhaltern abonnieren Muster Muster PSUBSCRIBE "logs.*" "chat.*" 1
  • 62. Publish/Subscribe S1 P1 "something happened" P2 logs.critical S2 P3 S3 Nachricht senden Channel Nachricht Publish "logs.warning" "something happened" 2
  • 63. Publish/Subscribe S1 P1 "something critical happened" "something critical happened" P2 logs.critical S2 P3 S3 Nachricht senden Channel Nachricht Publish "logs.critical" "something critical happened" 3
  • 64. Persistenz RDB - Dump  "point-in-time snapshot"  wird erstellt, wenn X Update-Operationen in Y Sekunden erfolgt  Standardeinstellungen: save 900 1 Dump, wenn mind. 1 Update in 15 Minuten save 300 10 Dump, wenn mind. 10 Updates in 5 Minuten save 60 10000 Dump, wenn mind. 10.000 Updates in 1 Minute  Vorteile:  Einspielen des Backups relativ schnell  Nachteile:  Datenverlust kann groß sein  Speichervorgang aufwendig (große Datenmenge)
  • 65. Persistenz AOF (append-only-file)  jeder einzelne Befehl geloggt  Wiedereinspielen der Daten durch Ausführung dieser Befehle  Schreib-Intervall konfigurierbar:  OS entscheidet (schnell)  jedes Query (langsam, aber sicher)  jede Sekunde (Kompromiss)  Vorteile:  relativ sicher, Datenverlust gering  Nachteile:  Einspielen des Backups langsam
  • 66. Persistenz RDB vs. AOF  keine Lösung besser oder schlechter als die andere => Entscheidung: Wie kritisch ist ein Datenverlust?  beides auch in Kombination nutzbar
  • 67. Skalierbarkeit Master-Slave-Replikation  1 Master, mehrere Slaves  Slaves können selbst weitere Slaves besitzen  Synchronisierung: Master -> Slave  Slaves können Schreiboperationen ausführen, aber nicht mit Master synchronisieren!  einfache Handhabung:  Server als Slave starten: redis-server --slaveof 127.0.0.1 6379  automatische Synchronisierung  Auto-Reconnect bei Verbindungsabbruch
  • 68. Skalierbarkeit Redis Cluster (noch in Alpha-Phase!)  bis zu 4096 Knoten  Ziel: lineare Skalierbarkeit  Schlüssel werden auf Knoten verteilt ("Consistent Hashing")  Redundanz-Faktor konfigurierbar ("Live-Backup")  Jeder Schlüssel existiert auf 1 Master + N Slaves (Slaves = read-only)  Fehlertoleranz:  Knoten "pingen" sich gegenseitig  bei Timeout wird Knoten als "nicht verfügbar" markiert (alle Knoten des Clusters werden informiert)  Wenn Knoten wieder online ist, wird er "runtergefahren" (mögliche Dateninkonsistenz)
  • 69. http://redis.io  http://www.cafebabe.me/2011/05/redis-pipelines-and- transactions.html
  • 70. Vielen Dank für die Aufmerksamkeit! Fragen?