๐Ÿ’ป Common Redis Commands ๐Ÿ’พ

Truong Phung - Oct 30 - - Dev Community

Here is a comprehensive example that covers a wide range of common Redis features:

A. Common Commands

1. Basic CRUD Operations

Set and Get Data

SET user:1:name "John Doe"
GET user:1:name
Enter fullscreen mode Exit fullscreen mode

Example with TTL (Time to Live)

SET session:1234 "session_data" EX 60   # Key will expire in 60 seconds
GET session:1234
TTL session:1234                       # Check how much time is left for the key
Enter fullscreen mode Exit fullscreen mode

2. Hashes

Hashes are used to store multiple fields and values under a single key.

Example: Using Hashes to Store User Information

HSET user:1 name "John Doe" email "john@example.com"
HGETALL user:1                    # Retrieve all fields and values
HGET user:1 email                  # Retrieve specific field
HDEL user:1 email                  # Delete specific field
Enter fullscreen mode Exit fullscreen mode

3. Lists

Lists are used to store an ordered sequence of elements.

Example: Using Lists for a Queue

RPUSH queue:tasks "task1" "task2"   # Add tasks to the right end of the list
LPOP queue:tasks                    # Remove the task from the left end
LRANGE queue:tasks 0 -1             # Get all tasks in the queue
Enter fullscreen mode Exit fullscreen mode

4. Sets

Sets are unordered collections of unique elements.

Example: Using Sets to Store Unique Tags

SADD tags "redis" "nosql" "database"
SMEMBERS tags                  # Get all members of the set
SISMEMBER tags "redis"         # Check if an element exists
SREM tags "nosql"              # Remove an element from the set
Enter fullscreen mode Exit fullscreen mode

5. Sorted Sets

Sorted Sets are like Sets but with an associated score for each member, which allows ordering.

Example: Using Sorted Sets for Leaderboards

ZADD leaderboard 1000 "user:1" 500 "user:2"
ZRANGE leaderboard 0 -1 WITHSCORES         # Get all members with scores
ZRANK leaderboard "user:1"                 # Get the rank of a specific member
ZINCRBY leaderboard 100 "user:1"           # Increment the score of a member
Enter fullscreen mode Exit fullscreen mode

6. Transactions

Transactions in Redis allow you to execute multiple commands in a single, atomic operation using MULTI and EXEC.

Example: Simple Transaction

MULTI
SET account:1:balance 100
INCRBY account:1:balance 50
DECRBY account:1:balance 25
EXEC
Enter fullscreen mode Exit fullscreen mode

7. Pipelining

Pipelining allows multiple commands to be sent to the server without waiting for a reply.

Example: Pipelining with Redis CLI

redis-cli --pipe
SET user:1 "John Doe"
SET user:2 "Jane Doe"
SET user:3 "Alice Smith"
Enter fullscreen mode Exit fullscreen mode

8. Pub/Sub (Publish/Subscribe)

Redis Pub/Sub allows for message broadcasting to multiple clients subscribed to a channel.

Example: Publish/Subscribe System

Publisher

PUBLISH news "Breaking News: Redis is awesome!"
Enter fullscreen mode Exit fullscreen mode

Subscriber

SUBSCRIBE news
Enter fullscreen mode Exit fullscreen mode

9. Lua Scripting

You can run Lua scripts in Redis for atomic and efficient processing.

Example: Lua Script for Incrementing a Key

EVAL "return redis.call('INCRBY', KEYS[1], ARGV[1])" 1 counter 10
Enter fullscreen mode Exit fullscreen mode

This script increments the value of counter by 10.

10. Expiration and Persistence

You can set expiration times for keys, or Redis can persist data using snapshots (RDB) or append-only files (AOF).

Example: Set Expiration

SET temp:key "temp_value" EX 10        # Key will expire after 10 seconds
Enter fullscreen mode Exit fullscreen mode

Example: Persistence Configuration

SAVE                                   # Force an RDB snapshot
BGSAVE                                 # Background save
Enter fullscreen mode Exit fullscreen mode

11. HyperLogLog

HyperLogLog is used for approximating the cardinality (i.e., number of unique elements) of large datasets.

Example: Counting Unique Visitors

PFADD unique_visitors "user1" "user2" "user3"
PFCOUNT unique_visitors                 # Approximate count of unique users
Enter fullscreen mode Exit fullscreen mode

12. Bitmaps

Redis allows bit-level operations on string values.

Example: Simple Bitmap Usage

SETBIT user:1:loggedin 0 1               # Set bit 0 to 1
GETBIT user:1:loggedin 0                 # Get bit 0
BITCOUNT user:1:loggedin                 # Count number of set bits
Enter fullscreen mode Exit fullscreen mode

13. Geospatial Indexes

Redis allows you to store, query, and perform operations on geospatial data.

Example: Geospatial Operations

GEOADD cities:locations 13.361389 38.115556 "Palermo"
GEOADD cities:locations 15.087269 37.502669 "Catania"
GEORADIUS cities:locations 15 37 100 km      # Find locations within 100 km
Enter fullscreen mode Exit fullscreen mode

14. Streams

Streams are a type of log structure that allows you to store and consume data in an append-only manner.

Example: Adding and Reading from a Stream

XADD mystream * name "John Doe" age 30
XRANGE mystream - +
Enter fullscreen mode Exit fullscreen mode

15. Redis Cluster

Redis supports clustering to scale horizontally.

Example: Create a Cluster

You would typically use redis-cli or a specialized tool for cluster setup, but the basic steps involve:

redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 --cluster-replicas 1
Enter fullscreen mode Exit fullscreen mode

16. Replication

Redis supports master-slave replication for high availability.

Example: Setting Up Replication

In the Redis configuration file (redis.conf):

replicaof 127.0.0.1 6379
Enter fullscreen mode Exit fullscreen mode

17. Redis Sentinel

Sentinel provides high availability through automatic failover.

Example: Starting Sentinel

redis-sentinel /path/to/sentinel.conf
Enter fullscreen mode Exit fullscreen mode

In the Sentinel config file:

sentinel monitor mymaster 127.0.0.1 6379 2
Enter fullscreen mode Exit fullscreen mode

18. Redis Modules

Redis Modules allow you to extend Redis with custom functionality.

Example: Loading a Redis Module

In the Redis config file:

loadmodule /path/to/module.so
Enter fullscreen mode Exit fullscreen mode

Modules like RedisGraph, RedisAI, and RediSearch are popular extensions.

19. Memory Management

Redis provides commands to monitor memory usage and optimize performance.

Example: Checking Memory Usage

INFO memory
Enter fullscreen mode Exit fullscreen mode

This provides detailed information about memory consumption, fragmentation, and key eviction policy.

20. EXPLAIN Command

While Redis doesnโ€™t have an equivalent to SQL EXPLAIN, you can use the DEBUG command to get insights into what the server is doing.

Example: DEBUG Command

DEBUG OBJECT keyname
Enter fullscreen mode Exit fullscreen mode

This shows metadata about a specific key, such as encoding, reference count, and idle time.

B. Other Advanced Commands

The comprehensive Redis example covers most common features, but here are a few additional advanced or specialized features that might be useful:

1. Scan Operations

Redis provides a way to iterate over large datasets without blocking.

Example: Iterating Over Keys (Non-Blocking)

SCAN 0 MATCH user:* COUNT 10
Enter fullscreen mode Exit fullscreen mode

SCAN is a cursor-based iteration over the dataset.

Example: Scanning a Hash

HSCAN user:1 0 MATCH field* COUNT 5
Enter fullscreen mode Exit fullscreen mode

2. Redis Memory Optimization

Example: Eviction Policies

Redis allows you to specify eviction policies for managing memory.

CONFIG SET maxmemory-policy allkeys-lru
Enter fullscreen mode Exit fullscreen mode

This setting enables the LRU (Least Recently Used) eviction policy.

Example: Memory Usage of Specific Key

MEMORY USAGE user:1
Enter fullscreen mode Exit fullscreen mode

This command returns the memory usage in bytes for the key user:1.

3. Keyspace Notifications

Redis can send notifications about keyspace events, such as expiration or modification of keys.

Example: Enabling Notifications

CONFIG SET notify-keyspace-events Ex
Enter fullscreen mode Exit fullscreen mode

This enables expiration notifications.

Example: Listening for Expiration Events

PSUBSCRIBE __keyevent@0__:expired
Enter fullscreen mode Exit fullscreen mode

This subscribes to events where keys in database 0 expire.

4. Stream Consumers and Consumer Groups

Stream Consumer Groups allow multiple consumers to read from the same stream independently.

Example: Creating and Using Consumer Groups

XGROUP CREATE mystream group1 0
XREADGROUP GROUP group1 consumer1 COUNT 1 STREAMS mystream >
Enter fullscreen mode Exit fullscreen mode

5. Redis Modules (Advanced)

While Redis Modules were mentioned, a more specific module like RedisJSON can be a powerful addition.

Example: Using RedisJSON Module

JSON.SET user:100 $ '{"name":"John","age":30}'
JSON.GET user:100 $.name
Enter fullscreen mode Exit fullscreen mode

RedisJSON allows you to store and manipulate JSON documents in Redis.

6. Bitfield Operations

The BITFIELD command allows you to manipulate integers stored in bits in a string.

Example: Bitfield Usage

BITFIELD mybits SET u8 100 255
Enter fullscreen mode Exit fullscreen mode

This sets an unsigned 8-bit integer at offset 100 to the value 255.

7. Scripting with Pipelining

While pipelining was covered, you can combine it with Lua scripting to optimize multiple commands in a single request.

Example: Atomic Update with Lua and Pipelining

EVAL "redis.call('SET', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[2], ARGV[2])" 2 key1 key2 value1 10
Enter fullscreen mode Exit fullscreen mode

8. RediSearch (Advanced)

If working with full-text search, RediSearch is a powerful Redis module.

Example: RediSearch Usage

FT.CREATE myIndex SCHEMA title TEXT WEIGHT 5.0 body TEXT
FT.ADD myIndex doc1 1.0 FIELDS title "Redis Modules" body "Search capabilities in Redis"
FT.SEARCH myIndex "Redis"
Enter fullscreen mode Exit fullscreen mode

This allows full-text search in Redis using the RediSearch module.

9. Bloom Filters (Probabilistic Data Structures)

Redis has built-in support for Bloom filters via RedisBloom module.

Example: Using Bloom Filter

BF.ADD myBloom "foo"
BF.EXISTS myBloom "foo"
BF.EXISTS myBloom "bar"
Enter fullscreen mode Exit fullscreen mode

Bloom filters provide space-efficient set-like functionality, with a small chance of false positives.

10. Redis Streams Advanced Features

While basic streams were covered, advanced stream features like trimming and acknowledging entries are also common.

Example: Trimming Streams

XADD mystream MAXLEN 1000 * name "Alice"
Enter fullscreen mode Exit fullscreen mode

Automatically trims the stream to maintain at most 1000 entries.

Example: Acknowledging Entries in Consumer Group

XACK mystream group1 1526569495637-0
Enter fullscreen mode Exit fullscreen mode

Acknowledge that a message has been processed by a consumer group.

Conclusion

This example covers almost all common Redis features, including basic CRUD operations, advanced data structures (hashes, lists, sets, sorted sets), pipelines, transactions, and specialized use cases (streams, geospatial data, and hyperloglog). It also touches on higher-level features like Lua scripting, clustering, replication, and Redis Sentinel for high availability.

Additionally, It mentions some more advanced use cases for Redis, including real-time analytics (bitfield, stream consumers), data modeling (RediSearch, RedisJSON), and optimization techniques (memory, keyspace notifications).

Redis is extremely versatile and this comprehensive example provides an overview of how it can be used across different scenarios.

If you found this helpful, let me know by leaving a ๐Ÿ‘ or a comment!, or if you think this post could help someone, feel free to share it! Thank you very much! ๐Ÿ˜ƒ

Read more about RESTful API with Redis

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player