You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
The String is the most fundamental Redis data type. Every other data type in Redis is built on top of it. A String value can hold text, integers, floating-point numbers, or raw binary data (such as a serialised JSON payload or an image), up to a maximum of 512 MB per value.
The two most basic commands are SET (store a value) and GET (retrieve it):
127.0.0.1:6379> SET username "alice"
OK
127.0.0.1:6379> GET username
"alice"
Keys are case-sensitive. If you SET a key that already exists, the old value is silently overwritten.
SET accepts options to control behaviour when a key already exists:
# NX — only set if the key does NOT exist
127.0.0.1:6379> SET lock "1" NX
OK
127.0.0.1:6379> SET lock "2" NX
(nil) # key already exists, nothing happened
# XX — only set if the key DOES exist
127.0.0.1:6379> SET lock "3" XX
OK
When a String value looks like an integer, Redis can increment or decrement it atomically without a read-modify-write cycle in application code:
127.0.0.1:6379> SET page_views 0
OK
127.0.0.1:6379> INCR page_views
(integer) 1
127.0.0.1:6379> INCRBY page_views 10
(integer) 11
127.0.0.1:6379> DECR page_views
(integer) 10
127.0.0.1:6379> DECRBY page_views 3
(integer) 7
INCR is atomic: even if two clients call it simultaneously, each increment is applied without race conditions.
You can attach a time-to-live to a string at set time:
# EX sets expiry in seconds
127.0.0.1:6379> SET session_token "abc123" EX 3600
OK
# PX sets expiry in milliseconds
127.0.0.1:6379> SET otp "987654" PX 300000
OK
Store or retrieve multiple keys in a single round trip:
127.0.0.1:6379> MSET first_name "Bob" last_name "Smith" city "London"
OK
127.0.0.1:6379> MGET first_name last_name city
1) "Bob"
2) "Smith"
3) "London"
127.0.0.1:6379> SET greeting "Hello"
OK
127.0.0.1:6379> APPEND greeting ", World!"
(integer) 13
127.0.0.1:6379> STRLEN greeting
(integer) 13
Strings are the building block for caching, counters, session tokens, and any simple key-value storage need in Redis.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.