SlideShare uma empresa Scribd logo
1 de 21
Baixar para ler offline
Introduction to Redis
Saeid Zebardast
@saeidzeb
zebardast.com
April 2015
1
Agenda
● What is Redis?
● Features
● Persistence
● Data types
● Commands
● Publish / Subscribe
● Sort
● Transactions
● Replication
● Cluster 2
What is Redis?
● Data structure server
● In-memory Key-Value store
○ it is also persistent!
● Open source, BSD licensed
3
Features
● Abstract data types
● Atomic operations
● Service-side operations
● Transactions
● Pub/Sub
● Lua scripting
● TTL (Time-to-Live)
● Master-Slave asynchronous replication
● Atomic Failover
4
Persistence
● Can be optionally disabled
● RDB file
○ Synchronized to disk (eventually or immediately)
○ Use SAVE or BGSAVE command to create a snapshot manually.
● Data is dumped or written as a append-only change-log (AOF)
● AOF mode supports transactional disk write
● Default config:
○ Save after 900 sec (15 min) if at least 1 key changed.
○ Save after 300 sec (5 min) if at least 10 keys changed.
○ Save after 60 sec if at least 10000 keys changed.
5
Data Types
● String (binary safe)
● Lists (linked lists)
● Sets
● Sorted sets (with scores)
● Hashes (<String, String>)
● Bitmaps (Bit arrays)
Note: The type of a value determines what operations (called commands) are available for the value itself.
6
Redis keys
● Binary safe
● Empty string is valid key
● Very long key is a bad idea
● Very short key is [often] a bad idea
○ u1000flw
● Stick with a schema
○ user:1000:followers
● Max allowed key size is 512 MB.
7
Basic commands
● SET key value [EX seconds] [PX milliseconds] [NX|XX]
○ MSET key value [key value ….]
● GET key
○ MGET key [key ….]
● INCR/DECR key
● INCRBY/DECRBY key increment
● DEL key
● EXISTS key
● EXPIRE key seconds
● TTL/PTTL key
● TYPE key
● MONITOR
● HELP command
8
Atomic Operations
● GETSET key value
○ Puts a new value, retrieving old one.
● SETNX key value
○ Sets a value only if it does not exist.
9
Strings
● Simplest type of value in Redis
● redis-cli> SET mykey value
OK
● redis-cli> GET mykey
“value”
● redis-cli> SET foo 110
OK
● redis-cli> INCR bar
(integer) 1
● redis-cli> INCRBY foo 50
(integer) 160
● Max allowed value size is 512 MB.
10
● Implemented by Linked List
● Push and pop at both sides
● BLPOP: Blocking POP
LPOP
BLPOP
Lists
A B C D
LPUSH RPUSH
RPOP
BRPOP
LRANGE
LINDEX
LSET
LREM
...
11
Sets
A, B, CSADD
B, C, D
SREM
SPOP
SISMEMBER
B, CSINTER
A, B, C, DSUNION
ASDIFF D
12
● Same as sets, but with score per element
Sorted Sets
foo | 12.1 bar | 14.3 baz | 17.87 qux | 30.9876
ZADD key score memeber [score memeber
...]
ZRANGE key start stop [withscores]
ZREVRANGE key start stop [WITHSCORES]
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset
count]
ZSCORE key member
ZRANK key member
13
Hashes
● redis-cli> HSET foo bar 1
(integer) 1
● redis-cli> HSET foo baz 2
(integer) 1
● redis-cli> SET foo foo foo
(integer) 1
● redis-cli> HGETALL foo
1) "bar"
2) "1"
3) "baz"
4) "1"
5) "foo”
6) "foo"
● redis-cli> HINCRBY foo bar 1
(integer) 2
● redis-cli> HGET foo bar
“2”
● redis-cli> HKEYS foo
1) "bar"
2) "baz"
3) "foo"
● redis-cli> HSCAN foo 0 MATCH *ba*
1) "0"
2)
1) "bar"
2) "3"
3) "baz"
4) "1" 14
Publish / Subscribe (PubSub)
● Clients can subscribe to channels or patterns.
● Subscribing is O(1), Posting message is O(N)
● Chats, Comet Apps, Real time analytics and etc.
On Client 1:
redis-cli> subscribe feed:foo feed:bar feed:baz
Reading messages...
On Client 2:
redis-cli> publish feed:foo “hello world!”
(integer) 1
On Client 1:
Reading messages...
1) "message"
2) "feed:foo"
3) "hello world!"
15
Sort
● SORT key
○ [BY pattern]
○ [LIMIT offset count]
○ [GET pattern [GET pattern ...]]
○ [ASC|DESC]
○ [ALPHA]
○ [STORE destination]
● By default, sorting is numeric and elements compared as double.
● Use the ALPHA modifier to sort string list lexicographically (UTF-8 aware).
● Result can be stored as a list.
16
Transactions
● MULTI, [commands], EXEC
● All commands are executed after EXEC.
● redis-cli> MULTI
OK
● redis-cli> SET foo bar
QUEUED
● redis-cli> INCRBY num 1
QUEUED
● redis-cli> EXEC
1) OK
2) (integer) 1
● DISCARD for discarding a transaction
● WATCH for locking keys
17
Replication
● Asynchronous, Non-Blocking Replication
● Turn on persistence in the Master or avoid restarting automatically.
● 64GB of memory i.e., Only 64GB of data
18
Redis Master Server
Redis Slave ServerRedis Slave ServerRedis Slave Server
Cluster
● Version 3.0 or higher. (Current stable version is 2.8)
● Automatically split your dataset among multiple nodes.
● Continue operations when a subset of the nodes are experiencing failures.
● 10 clustered computers with each 64GB of RAM, store 640GB of data.
19
Where Can I Learn More?
● redis.io
● redis.io/topics/quickstart
● try.redis.io
20
Thank You
Any
Questions,
Comments?
Saeid Zebardast
@saeidzeb
zebardast.com
April 2015
21

Mais conteúdo relacionado

Mais procurados

Андрей Годин - Базы данных: Документоориентированная горизонтально масштабиру...
Андрей Годин - Базы данных: Документоориентированная горизонтально масштабиру...Андрей Годин - Базы данных: Документоориентированная горизонтально масштабиру...
Андрей Годин - Базы данных: Документоориентированная горизонтально масштабиру...
Yandex
 
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
Karel Minarik
 
Rubyスクリプト
RubyスクリプトRubyスクリプト
Rubyスクリプト
Ayumu Hanba
 

Mais procurados (20)

MazuV-Debug-System
MazuV-Debug-SystemMazuV-Debug-System
MazuV-Debug-System
 
Redis modules 101
Redis modules 101Redis modules 101
Redis modules 101
 
Like loggly using open source
Like loggly using open sourceLike loggly using open source
Like loggly using open source
 
Configuring Syslog by Octavio
Configuring Syslog by OctavioConfiguring Syslog by Octavio
Configuring Syslog by Octavio
 
Андрей Годин - Базы данных: Документоориентированная горизонтально масштабиру...
Андрей Годин - Базы данных: Документоориентированная горизонтально масштабиру...Андрей Годин - Базы данных: Документоориентированная горизонтально масштабиру...
Андрей Годин - Базы данных: Документоориентированная горизонтально масштабиру...
 
Tales Of The Black Knight - Keeping EverythingMe running
Tales Of The Black Knight - Keeping EverythingMe runningTales Of The Black Knight - Keeping EverythingMe running
Tales Of The Black Knight - Keeping EverythingMe running
 
Redis - N✮SQL Berlin
Redis - N✮SQL BerlinRedis - N✮SQL Berlin
Redis - N✮SQL Berlin
 
SDE TP 4 - Processus
SDE TP 4 - ProcessusSDE TP 4 - Processus
SDE TP 4 - Processus
 
Don’t turn your logs into cuneiform
Don’t turn your logs into cuneiformDon’t turn your logs into cuneiform
Don’t turn your logs into cuneiform
 
Debugging TV Frame 0x06
Debugging TV Frame 0x06Debugging TV Frame 0x06
Debugging TV Frame 0x06
 
Bsdtw17: mariusz zaborski: case studies of sandboxing base system with capsicum
Bsdtw17: mariusz zaborski: case studies of sandboxing base system with capsicumBsdtw17: mariusz zaborski: case studies of sandboxing base system with capsicum
Bsdtw17: mariusz zaborski: case studies of sandboxing base system with capsicum
 
libuv: cross platform asynchronous i/o
libuv: cross platform asynchronous i/olibuv: cross platform asynchronous i/o
libuv: cross platform asynchronous i/o
 
Tomáš Čorej: Configuration management & CFEngine3
Tomáš Čorej: Configuration management & CFEngine3Tomáš Čorej: Configuration management & CFEngine3
Tomáš Čorej: Configuration management & CFEngine3
 
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
 
Rubyスクリプト
RubyスクリプトRubyスクリプト
Rubyスクリプト
 
MessagePack - An efficient binary serialization format
MessagePack - An efficient binary serialization formatMessagePack - An efficient binary serialization format
MessagePack - An efficient binary serialization format
 
Cryptography for Smalltalkers
Cryptography for SmalltalkersCryptography for Smalltalkers
Cryptography for Smalltalkers
 
Redis clustering
Redis clusteringRedis clustering
Redis clustering
 
Mastering JUNOS DHCP
Mastering JUNOS DHCPMastering JUNOS DHCP
Mastering JUNOS DHCP
 
A deep dive into libuv
A deep dive into libuvA deep dive into libuv
A deep dive into libuv
 

Destaque

Destaque (8)

What is REST?
What is REST?What is REST?
What is REST?
 
What is good design?
What is good design?What is good design?
What is good design?
 
How to be different?
How to be different?How to be different?
How to be different?
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
معرفی سیستم‌های توکار در دانشگاه صنعتی شریف
معرفی سیستم‌های توکار در دانشگاه صنعتی شریفمعرفی سیستم‌های توکار در دانشگاه صنعتی شریف
معرفی سیستم‌های توکار در دانشگاه صنعتی شریف
 
مستندات رفتاری در انجمنهای نرم افزار های آزاد
مستندات رفتاری در انجمنهای نرم افزار های آزادمستندات رفتاری در انجمنهای نرم افزار های آزاد
مستندات رفتاری در انجمنهای نرم افزار های آزاد
 
Web Components Revolution
Web Components RevolutionWeb Components Revolution
Web Components Revolution
 
Java for beginners
Java for beginnersJava for beginners
Java for beginners
 

Semelhante a Introduction to Redis

Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
Dvir Volk
 
Ramp-Tutorial for MYSQL Cluster - Scaling with Continuous Availability
Ramp-Tutorial for MYSQL Cluster - Scaling with Continuous AvailabilityRamp-Tutorial for MYSQL Cluster - Scaling with Continuous Availability
Ramp-Tutorial for MYSQL Cluster - Scaling with Continuous Availability
Pythian
 

Semelhante a Introduction to Redis (20)

Introduction to redis - version 2
Introduction to redis - version 2Introduction to redis - version 2
Introduction to redis - version 2
 
How to build TiDB
How to build TiDBHow to build TiDB
How to build TiDB
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
TriHUG 3/14: HBase in Production
TriHUG 3/14: HBase in ProductionTriHUG 3/14: HBase in Production
TriHUG 3/14: HBase in Production
 
TokuDB vs RocksDB
TokuDB vs RocksDBTokuDB vs RocksDB
TokuDB vs RocksDB
 
Demystifying MS17-010: Reverse Engineering the ETERNAL Exploits
Demystifying MS17-010: Reverse Engineering the ETERNAL ExploitsDemystifying MS17-010: Reverse Engineering the ETERNAL Exploits
Demystifying MS17-010: Reverse Engineering the ETERNAL Exploits
 
Understanding the architecture of MariaDB ColumnStore
Understanding the architecture of MariaDB ColumnStoreUnderstanding the architecture of MariaDB ColumnStore
Understanding the architecture of MariaDB ColumnStore
 
Data efficiency on BEAM - Choose the right data representation by Dmytro Lyto...
Data efficiency on BEAM - Choose the right data representation by Dmytro Lyto...Data efficiency on BEAM - Choose the right data representation by Dmytro Lyto...
Data efficiency on BEAM - Choose the right data representation by Dmytro Lyto...
 
2019.06.27 Intro to Ceph
2019.06.27 Intro to Ceph2019.06.27 Intro to Ceph
2019.06.27 Intro to Ceph
 
Fluentd vs. Logstash for OpenStack Log Management
Fluentd vs. Logstash for OpenStack Log ManagementFluentd vs. Logstash for OpenStack Log Management
Fluentd vs. Logstash for OpenStack Log Management
 
BUD17-302: LLVM Internals #2
BUD17-302: LLVM Internals #2 BUD17-302: LLVM Internals #2
BUD17-302: LLVM Internals #2
 
Ramp-Tutorial for MYSQL Cluster - Scaling with Continuous Availability
Ramp-Tutorial for MYSQL Cluster - Scaling with Continuous AvailabilityRamp-Tutorial for MYSQL Cluster - Scaling with Continuous Availability
Ramp-Tutorial for MYSQL Cluster - Scaling with Continuous Availability
 
Auto Tuning
Auto TuningAuto Tuning
Auto Tuning
 
BUD17-310: Introducing LLDB for linux on Arm and AArch64
BUD17-310: Introducing LLDB for linux on Arm and AArch64 BUD17-310: Introducing LLDB for linux on Arm and AArch64
BUD17-310: Introducing LLDB for linux on Arm and AArch64
 
MariaDB / MySQL tripping hazard and how to get out again?
MariaDB / MySQL tripping hazard and how to get out again?MariaDB / MySQL tripping hazard and how to get out again?
MariaDB / MySQL tripping hazard and how to get out again?
 
M|18 Understanding the Architecture of MariaDB ColumnStore
M|18 Understanding the Architecture of MariaDB ColumnStoreM|18 Understanding the Architecture of MariaDB ColumnStore
M|18 Understanding the Architecture of MariaDB ColumnStore
 
A Brief Introduction of TiDB (Percona Live)
A Brief Introduction of TiDB (Percona Live)A Brief Introduction of TiDB (Percona Live)
A Brief Introduction of TiDB (Percona Live)
 
Logs @ OVHcloud
Logs @ OVHcloudLogs @ OVHcloud
Logs @ OVHcloud
 
Query and audit logging in cassandra
Query and audit logging in cassandraQuery and audit logging in cassandra
Query and audit logging in cassandra
 

Mais de Saeid Zebardast

Mais de Saeid Zebardast (7)

An Introduction to Apache Cassandra
An Introduction to Apache CassandraAn Introduction to Apache Cassandra
An Introduction to Apache Cassandra
 
An overview of Scalable Web Application Front-end
An overview of Scalable Web Application Front-endAn overview of Scalable Web Application Front-end
An overview of Scalable Web Application Front-end
 
MySQL Cheat Sheet
MySQL Cheat SheetMySQL Cheat Sheet
MySQL Cheat Sheet
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Developing Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersDeveloping Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginners
 
هفده اصل افراد موثر در تیم
هفده اصل افراد موثر در تیمهفده اصل افراد موثر در تیم
هفده اصل افراد موثر در تیم
 
معرفی گنو/لینوکس و سیستم عامل های متن باز و آزاد
معرفی گنو/لینوکس و سیستم عامل های متن باز و آزادمعرفی گنو/لینوکس و سیستم عامل های متن باز و آزاد
معرفی گنو/لینوکس و سیستم عامل های متن باز و آزاد
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
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
Safe Software
 

Último (20)

Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
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 New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
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
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

Introduction to Redis

  • 1. Introduction to Redis Saeid Zebardast @saeidzeb zebardast.com April 2015 1
  • 2. Agenda ● What is Redis? ● Features ● Persistence ● Data types ● Commands ● Publish / Subscribe ● Sort ● Transactions ● Replication ● Cluster 2
  • 3. What is Redis? ● Data structure server ● In-memory Key-Value store ○ it is also persistent! ● Open source, BSD licensed 3
  • 4. Features ● Abstract data types ● Atomic operations ● Service-side operations ● Transactions ● Pub/Sub ● Lua scripting ● TTL (Time-to-Live) ● Master-Slave asynchronous replication ● Atomic Failover 4
  • 5. Persistence ● Can be optionally disabled ● RDB file ○ Synchronized to disk (eventually or immediately) ○ Use SAVE or BGSAVE command to create a snapshot manually. ● Data is dumped or written as a append-only change-log (AOF) ● AOF mode supports transactional disk write ● Default config: ○ Save after 900 sec (15 min) if at least 1 key changed. ○ Save after 300 sec (5 min) if at least 10 keys changed. ○ Save after 60 sec if at least 10000 keys changed. 5
  • 6. Data Types ● String (binary safe) ● Lists (linked lists) ● Sets ● Sorted sets (with scores) ● Hashes (<String, String>) ● Bitmaps (Bit arrays) Note: The type of a value determines what operations (called commands) are available for the value itself. 6
  • 7. Redis keys ● Binary safe ● Empty string is valid key ● Very long key is a bad idea ● Very short key is [often] a bad idea ○ u1000flw ● Stick with a schema ○ user:1000:followers ● Max allowed key size is 512 MB. 7
  • 8. Basic commands ● SET key value [EX seconds] [PX milliseconds] [NX|XX] ○ MSET key value [key value ….] ● GET key ○ MGET key [key ….] ● INCR/DECR key ● INCRBY/DECRBY key increment ● DEL key ● EXISTS key ● EXPIRE key seconds ● TTL/PTTL key ● TYPE key ● MONITOR ● HELP command 8
  • 9. Atomic Operations ● GETSET key value ○ Puts a new value, retrieving old one. ● SETNX key value ○ Sets a value only if it does not exist. 9
  • 10. Strings ● Simplest type of value in Redis ● redis-cli> SET mykey value OK ● redis-cli> GET mykey “value” ● redis-cli> SET foo 110 OK ● redis-cli> INCR bar (integer) 1 ● redis-cli> INCRBY foo 50 (integer) 160 ● Max allowed value size is 512 MB. 10
  • 11. ● Implemented by Linked List ● Push and pop at both sides ● BLPOP: Blocking POP LPOP BLPOP Lists A B C D LPUSH RPUSH RPOP BRPOP LRANGE LINDEX LSET LREM ... 11
  • 12. Sets A, B, CSADD B, C, D SREM SPOP SISMEMBER B, CSINTER A, B, C, DSUNION ASDIFF D 12
  • 13. ● Same as sets, but with score per element Sorted Sets foo | 12.1 bar | 14.3 baz | 17.87 qux | 30.9876 ZADD key score memeber [score memeber ...] ZRANGE key start stop [withscores] ZREVRANGE key start stop [WITHSCORES] ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count] ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count] ZSCORE key member ZRANK key member 13
  • 14. Hashes ● redis-cli> HSET foo bar 1 (integer) 1 ● redis-cli> HSET foo baz 2 (integer) 1 ● redis-cli> SET foo foo foo (integer) 1 ● redis-cli> HGETALL foo 1) "bar" 2) "1" 3) "baz" 4) "1" 5) "foo” 6) "foo" ● redis-cli> HINCRBY foo bar 1 (integer) 2 ● redis-cli> HGET foo bar “2” ● redis-cli> HKEYS foo 1) "bar" 2) "baz" 3) "foo" ● redis-cli> HSCAN foo 0 MATCH *ba* 1) "0" 2) 1) "bar" 2) "3" 3) "baz" 4) "1" 14
  • 15. Publish / Subscribe (PubSub) ● Clients can subscribe to channels or patterns. ● Subscribing is O(1), Posting message is O(N) ● Chats, Comet Apps, Real time analytics and etc. On Client 1: redis-cli> subscribe feed:foo feed:bar feed:baz Reading messages... On Client 2: redis-cli> publish feed:foo “hello world!” (integer) 1 On Client 1: Reading messages... 1) "message" 2) "feed:foo" 3) "hello world!" 15
  • 16. Sort ● SORT key ○ [BY pattern] ○ [LIMIT offset count] ○ [GET pattern [GET pattern ...]] ○ [ASC|DESC] ○ [ALPHA] ○ [STORE destination] ● By default, sorting is numeric and elements compared as double. ● Use the ALPHA modifier to sort string list lexicographically (UTF-8 aware). ● Result can be stored as a list. 16
  • 17. Transactions ● MULTI, [commands], EXEC ● All commands are executed after EXEC. ● redis-cli> MULTI OK ● redis-cli> SET foo bar QUEUED ● redis-cli> INCRBY num 1 QUEUED ● redis-cli> EXEC 1) OK 2) (integer) 1 ● DISCARD for discarding a transaction ● WATCH for locking keys 17
  • 18. Replication ● Asynchronous, Non-Blocking Replication ● Turn on persistence in the Master or avoid restarting automatically. ● 64GB of memory i.e., Only 64GB of data 18 Redis Master Server Redis Slave ServerRedis Slave ServerRedis Slave Server
  • 19. Cluster ● Version 3.0 or higher. (Current stable version is 2.8) ● Automatically split your dataset among multiple nodes. ● Continue operations when a subset of the nodes are experiencing failures. ● 10 clustered computers with each 64GB of RAM, store 640GB of data. 19
  • 20. Where Can I Learn More? ● redis.io ● redis.io/topics/quickstart ● try.redis.io 20