Table of contents
Open Table of contents
Learning Redis
Basic Usage
Starting Redis
# Start the Redis server.
redis-server --port 6379
# When there are multiple Redis instances, specify a configuration file at startup.
redis-server ./redis.conf
redis-server ./redis16379.conf
# Start the Redis client.
redis-cli -p 6379
Shutting Down
redis-cli shutdown
Checking the Redis Connection
ping
# A PONG response means the connection is working.
Getting Started
-
Add a key.
SET bar 1 -
Get all keys in Redis.
# Not recommended in production, where there may be many keys. # Supports ? for one character, * for any characters, and [] for a range: a[b-d] matches ab, ac, and ad. KEYS * -
Check whether a key exists.
EXISTS bar # Returns 1 if it exists. -
Delete a key.
DEL bar # Returns the number of keys deleted: 1 here. DEL bar1 bar2 # The returned number is 2 here. DEL bar # Returns 0 because no key was deleted; bar was already removed by the first command. -
Check a key’s type.
# Returns string here. TYPE bar
Basic Data Types
Strings
Each key of the string type corresponds to just one string.
-
Set and get values.
# Set the value of the dhb key to hello. SET dhb hello # Returns OK on success. GET dhb # Returns "hello". -
Append to an existing string.
# Append world to the dhb key. Returns the total string length after appending: 10 here. APPEND dhb world -
Get a string’s length.
# Get the length of the string stored at dhb. STRLEN dhb -
Set multiple key-value pairs at once.
# Set git to github and svn to svnhub. MSET git github svn svnHub # Syntax MSET key1 value1 key2 value2 -
Get values for multiple keys at once.
# Get the values corresponding to git and svn. MGET git svn # Syntax MGET key1 key2 -
Increment a number.
# Increment the jack key. INCR jack # Returns the value after incrementing. # Returns 1 here because the key did not initially exist.Question: if two Redis clients connect to the same Redis instance and both call INCR, could they both read an initial value of 1 at the same instant, each add 1, and cause Redis to update the value to 2 instead of the expected 3? How is this handled?
Answer: all Redis commands are atomic operations. The situation above will not occur, regardless of how many clients are connected.
-
Decrement a number.
# Decrement dhb and return the resulting value. DECR dhb -
Add a specified integer.
# Add 4 to dhb; again, return the resulting value. INCRBY dhb 4 -
Subtract a specified integer.
# Subtract 4 from dhb and return the resulting value. DECRBY dhb 4 -
Add a specified floating-point number.
# Add 3.2 to dhb and return the resulting value. INCRBYFLOAT dhb 3.2Note that Redis does not provide a command for subtracting a specified floating-point number.
Hashes
A hash key can contain $2^{32}-1$ fields. Hashes are suitable for storing objects, with an object’s properties stored in separate fields.
-
Set and get values.
# Set the price field of car to 500. HSET car price 500 # Get the value of the price field of car. HGET car price -
Set multiple field-value pairs at once.
# Set the name and address fields of car to benchi and china, respectively. HMSET car name benchi address china # Syntax HMSET key field1 value1 field2 value2 -
Get multiple field values from an object at once.
# Get the name and address fields of car. HMGET car name address -
Get all fields of a key.
HGETALL car # Returns fields followed by their values. 1) "price" 2) "500" 3) "name" 4) "benchi" 5) "address" 6) "china" -
Check whether a field exists.
# Check whether the name field of car exists. HEXISTS car name # Returns 1 if it exists, or 0 otherwise. -
Set a field only if it does not exist.
# Set the num field of car to 112 if absent; otherwise do nothing. HSETNX car num 112 -
Add a number to a field.
# Add 45 to the price field of car and return the resulting value. HINCRBY car price 45 # Although there is no subtraction operation, adding a negative number implements subtraction. HINCRBY car price -34 -
Delete fields.
# Delete the price and name fields of car. Returns the number deleted: 2 here. HDEL car price name -
Get only the field names.
# Get all field names of car. HKEYS car -
Get only the field values.
# Get all field values of car. HVALS car -
Get the number of fields.
# Get the number of fields in car; returns the field count. HLEN car
Lists
Lists are commonly used for adding elements at either end.
-
Add elements at either end of a list.
# Add an element to the left end of mynum. LPUSH mynum 1 # Add two elements to the left end of mynum. LPUSH mynum 3 8 # Add an element to the right end of mynum. RPUSH mynum 2 # Add two elements to the right end of mynum. RPUSH mynum 3 8 # Returns the list length after adding the elements. -
Get the number of elements in a list.
# Get the number of elements in mynum. LLEN car -
Pop elements from either end of a list.
# Pop an element from the left end of mynum and return it. LPOP mynum # Pop an element from the right end of mynum and return it. RPOP mynum # B means block: wait until an element is available before popping it. When mynum, mynum1, and mynum2 all have values, keys are considered in order. This is useful for multiple task queues with different priorities. BRPOP mynum mynum1 mynum3 -
Get a range of list elements. LRANGE only returns elements without deleting them; LPOP and RPOP delete the elements they return.
# Get elements at indexes 2 through 5 in mynum: indexes 2, 3, 4, and 5. LRANGE mynum 2 5 Negative indexes can be used to indicate the Nth element from the right. LRANG mynum 2 -1 # Syntax LRANGE key start stopIf start is positioned after stop, an empty list is returned, for example:
LRANG mynum -1 2 # Returns empty list or set.If stop exceeds the actual index range, elements through the rightmost end of the list are returned, for example:
LRANGE mynum 2 999 # Returns all elements from index 2 through the actual end of the list. -
Remove specified values from a list.
# Remove the first 3 occurrences of 4 from the left. LREM mynum 3 4 # Remove the first 2 occurrences of 5 from the right. LREM mynum -2 5 # Remove all occurrences of 3. LREM mynum 0 3 -
Insert an element at a particular position in a list.
# Insert 7 before the element 1 in mycar. LINSERT mycar before 1 7 # Syntax LINSERT key before/after pivot value -
Move the element at the tail of one list to the head of another.
# Pop the tail of mycar and push it onto the head of myhouse. The lists may be the same, making this a rotation that moves an element to the head. RPOPLPUSH mycar myhouse # Returns the element's value.
Sets
Elements in a set are unique; duplicates are not allowed. Lists, by contrast, can contain multiple identical elements.
-
Add and remove elements.
# Add the three elements 1, 2, and 3 to setA. SADD setA 1 2 3 # Remove 1 and 3 from setA. SREM setA 1 3 -
Get all elements of a set.
# Get all elements of setA. SMEMBERS setA -
Check whether an element exists in a set.
# Check whether setA contains 2; returns 1 if present, or 0 otherwise. SISMEMBER setA 2 -
Set difference, intersection, and union.
# Find the difference between set A and set B: elements in A but not in B. SDIFF setA setB # Multiple sets are supported; difference, intersection, and union are computed in order. SDIFF setA setB setC # First find A minus B, then find the difference between that result and C. # Find the intersection of sets A and B. SINTER setA setB # Find the union of sets A and B. SUNION setA setB -
Get the number of elements in a set; returns the total element count.
SCARD setA -
Get random elements from a set.
# Get random elements from the set. SRANDMEMBER setA 1 # Syntax SRANDMEMBER key [count] # If count is positive, return count distinct random elements; if count exceeds the set size, return all elements. # If count is negative, return |count| random elements, possibly with duplicates. -
Pop an element from a set.
SPOP setB
Sorted Sets
Elements are automatically ordered by score.
-
Add and remove elements.
# Add tom and anmi to the sorted set zset, ordered automatically by their scores. ZADD zset 78 tom 89 anmi ZREM zset tom -
Get an element’s score.
# Get the score of tom in zset. ZSCORE zset tom -
Increase an element’s score.
# Add 12 to tom's score in zset and return the resulting score. ZINCRBY zset 12 tom -
Get elements within an index range: ZRANGE and ZREVRANGE.
# Get elements at indexes 0 through 2 in zset, in ascending order. ZRANGE zset 0 2 # Returns tom anmi jack. # To retrieve the corresponding scores as well: ZRANGE zset 0 2 WITHSCORES # Returns tom 78 anmi 89 jack 99. ZREVRANGE returns elements in descending order.If two elements have the same score, they are ordered by their ASCII values. For Chinese text, this depends on the encoding; the text is ultimately converted to ASCII values for sorting.
-
Get elements within a score range.
# Get elements of zset whose scores are >=10 and <=50. ZRANGEBYSCORE zst 10 50 # To retrieve the corresponding scores as well: ZRANGEBYSCORE zst 10 50 WITHSCORES # Use ( to exclude either or both endpoints, for example scores >=10 and <50. ZRANGEBYSCORE zset 10 (50 # Get the first three elements with scores between 10 and 50 in zset. Remember that this is ascending order; use ZREVRANGEBYSCORE for descending order. ZRANGEBYSCORE zset 10 50 LIMIT 0 3 # Syntax ZRANGEBYSCORE key min max LIMIT offset count -
Get the number of elements in the set.
ZCARD zset -
Get the number of elements within a specified score range.
ZCOUNT zset 10 50 -
Get an element’s rank.
# Get its rank in ascending order. ZRANK zset jack # For descending order, use: ZREVRANK zset jack -
Remove elements within a specified score range.
# Remove elements from zset whose scores are >=10 and <=20. ZREMRANGEBYSCORE zset 10 20
Notes
- Redis commands are case-insensitive.
- A useful convention for Redis key names is object-type:object-ID:object-property.
Useful Resources
- Redis command reference: useful for a quick search when you forget a command.
- Redis documentation: official documentation is always my first recommendation for getting started and solving problems.
Terminology
- Time To Live (TTL): the time an item remains alive.
- Race Condition: a condition caused by competing operations.
- Round-trip delay time (round trip time): the delay for a round trip.
Business Atomicity and Code Atomicity When Using a Redis Java Client
When writing application code, some developers know to use Redis for atomic operations and assemble business logic through a Java client, but overlook the atomicity of the entire business operation. In such cases, use a Lua script rather than splitting critical business logic into individual lines of code, each making its own Redis call. Each Redis command is atomic, but the full code flow can still be affected by concurrent threads. Critical business operations that require atomicity therefore need to be implemented with Lua scripts.