Here's a comprehensive Redis Command DEMO​ covering all major Redis data types and operations with practical examples:

1. Installation and Setup

First, ensure Redis is installed and running:

# Install Redis (Ubuntu/Debian)
sudo apt update
sudo apt install redis-server

# Start Redis server
sudo systemctl start redis-server
sudo systemctl enable redis-server

# Connect to Redis CLI
redis-cli

2. Basic Connection and Configuration

# Connect to Redis
redis-cli

# Test connection
127.0.0.1:6379> PING
PONG

# Get Redis info
127.0.0.1:6379> INFO server
127.0.0.1:6379> CONFIG GET maxmemory
127.0.0.1:6379> CONFIG SET maxmemory 256mb

# Select database (0-15)
127.0.0.1:6379> SELECT 1
127.0.0.1:6379[1]> SELECT 0

3. STRING Operations

# Basic SET and GET
127.0.0.1:6379> SET username "john_doe"
OK
127.0.0.1:6379> GET username
"john_doe"

# SET with expiration
127.0.0.1:6379> SET session_token "abc123xyz" EX 3600
OK
127.0.0.1:6379> TTL session_token
(integer) 3598

# Multiple SET and GET
127.0.0.1:6379> MSET first_name "John" last_name "Doe" email "john@example.com"
OK
127.0.0.1:6379> MGET first_name last_name email
1) "John"
2) "Doe"
3) "john@example.com"

# Numeric operations
127.0.0.1:6379> SET counter 10
OK
127.0.0.1:6379> INCR counter
(integer) 11
127.0.0.1:6379> INCRBY counter 5
(integer) 16
127.0.0.1:6379> DECR counter
(integer) 15
127.0.0.1:6379> DECRBY counter 3
(integer) 12

# APPEND and STRLEN
127.0.0.1:6379> SET greeting "Hello"
OK
127.0.0.1:6379> APPEND greeting " World"
(integer) 11
127.0.0.1:6379> GET greeting
"Hello World"
127.0.0.1:6379> STRLEN greeting
(integer) 11

# EXISTS and DELETE
127.0.0.1:6379> EXISTS username
(integer) 1
127.0.0.1:6379> DEL username
(integer) 1
127.0.0.1:6379> EXISTS username
(integer) 0

# SETNX (SET if Not eXists)
127.0.0.1:6379> SETNX lock_key "locked" EX 10
(integer) 1
127.0.0.1:6379> SETNX lock_key "new_lock"  # Already exists
(integer) 0

4. HASH Operations

# Basic HSET and HGET
127.0.0.1:6379> HSET user:1000 name "Alice" age "30" city "New York"
(integer) 3
127.0.0.1:6379> HGET user:1000 name
"Alice"
127.0.0.1:6379> HGETALL user:1000
1) "name"
2) "Alice"
3) "age"
4) "30"
5) "city"
6) "New York"

# HMSET and HMGET
127.0.0.1:6379> HMSET product:2001 name "Laptop" price "999.99" stock "50"
OK
127.0.0.1:6379> HMGET product:2001 name price stock
1) "Laptop"
2) "999.99"
3) "50"

# HINCRBY for numeric fields
127.0.0.1:6379> HINCRBY user:1000 age 1
(integer) 31
127.0.0.1:6379> HINCRBY product:2001 stock -5
(integer) 45

# HEXISTS and HDEL
127.0.0.1:6379> HEXISTS user:1000 email
(integer) 0
127.0.0.1:6379> HDEL user:1000 city
(integer) 1

# HKEYS, HVALS, HLEN
127.0.0.1:6379> HKEYS user:1000
1) "name"
2) "age"
127.0.0.1:6379> HVALS user:1000
1) "Alice"
2) "31"
127.0.0.1:6379> HLEN user:1000
(integer) 2

# HSETNX (set if not exists)
127.0.0.1:6379> HSETNX user:1000 email "alice@example.com"
(integer) 1
127.0.0.1:6379> HSETNX user:1000 email "new@example.com"
(integer) 0

5. LIST Operations

# LPUSH and RPUSH (left and right push)
127.0.0.1:6379> LPUSH tasks "task1"
(integer) 1
127.0.0.1:6379> LPUSH tasks "task2"
(integer) 2
127.0.0.1:6379> RPUSH tasks "task3"
(integer) 3
127.0.0.1:6379> LRANGE tasks 0 -1
1) "task2"
2) "task1"
3) "task3"

# LPOP and RPOP
127.0.0.1:6379> LPOP tasks
"task2"
127.0.0.1:6379> RPOP tasks
"task3"
127.0.0.1:6379> LRANGE tasks 0 -1
1) "task1"

# LINDEX and LLEN
127.0.0.1:6379> LPUSH queue "item1" "item2" "item3"
(integer) 3
127.0.0.1:6379> LINDEX queue 1
"item2"
127.0.0.1:6379> LLEN queue
(integer) 3

# LREM (remove elements)
127.0.0.1:6379> RPUSH numbers 1 2 3 2 4 2
(integer) 6
127.0.0.1:6379> LREM numbers 2 2  # Remove 2 occurrences of '2'
(integer) 2
127.0.0.1:6379> LRANGE numbers 0 -1
1) "1"
2) "3"
3) "4"
4) "2"

# LTRIM (trim list to specified range)
127.0.0.1:6379> LPUSH logs "log1" "log2" "log3" "log4" "log5"
(integer) 5
127.0.0.1:6379> LTRIM logs 0 2  # Keep only first 3 elements
OK
127.0.0.1:6379> LRANGE logs 0 -1
1) "log5"
2) "log4"
3) "log3"

# Blocking operations (useful for queues)
127.0.0.1:6379> BRPOP waiting_queue 5  # Wait 5 seconds for element
(nil)

6. SET Operations

# SADD and SMEMBERS
127.0.0.1:6379> SADD tags "redis" "database" "nosql" "cache"
(integer) 4
127.0.0.1:6379> SMEMBERS tags
1) "cache"
2) "database"
3) "nosql"
4) "redis"

# SISMEMBER (check membership)
127.0.0.1:6379> SISMEMBER tags "redis"
(integer) 1
127.0.0.1:6379> SISMEMBER tags "mysql"
(integer) 0

# SCARD (cardinality - number of elements)
127.0.0.1:6379> SCARD tags
(integer) 4

# SREM (remove elements)
127.0.0.1:6379> SREM tags "cache"
(integer) 1
127.0.0.1:6379> SMEMBERS tags
1) "database"
2) "nosql"
3) "redis"

# SPOP (pop random element)
127.0.0.1:6379> SADD lottery_numbers 1 2 3 4 5 6 7 8 9 10
(integer) 10
127.0.0.1:6379> SPOP lottery_numbers
"7"
127.0.0.1:6379> SPOP lottery_numbers 3  # Pop 3 elements
1) "2"
2) "9"
3) "1"

# SUNION, SINTER, SDIFF (set operations)
127.0.0.1:6379> SADD set1 "a" "b" "c" "d"
(integer) 4
127.0.0.1:6379> SADD set2 "c" "d" "e" "f"
(integer) 4

127.0.0.1:6379> SUNION set1 set2
1) "a"
2) "b"
3) "c"
4) "d"
5) "e"
6) "f"

127.0.0.1:6379> SINTER set1 set2
1) "c"
2) "d"

127.0.0.1:6379> SDIFF set1 set2
1) "a"
2) "b"

7. SORTED SET (ZSET) Operations

# ZADD and ZRANGE
127.0.0.1:6379> ZADD leaderboard 100 "player1" 200 "player2" 150 "player3"
(integer) 3
127.0.0.1:6379> ZRANGE leaderboard 0 -1
1) "player1"
2) "player3"
3) "player2"

# ZREVRANGE (reverse order - highest first)
127.0.0.1:6379> ZREVRANGE leaderboard 0 -1 WITHSCORES
1) "player2"
2) "200"
3) "player3"
4) "150"
5) "player1"
6) "100"

# ZRANK and ZREVRANK (get rank)
127.0.0.1:6379> ZRANK leaderboard "player3"
(integer) 1
127.0.0.1:6379> ZREVRANK leaderboard "player3"
(integer) 1

# ZINCRBY (increment score)
127.0.0.1:6379> ZINCRBY leaderboard 50 "player1"
"150"
127.0.0.1:6379> ZREVRANGE leaderboard 0 -1 WITHSCORES
1) "player2"
2) "200"
3) "player3"
4) "150"
5) "player1"
6) "150"

# ZRANGEBYSCORE (range by score)
127.0.0.1:6379> ZADD scores 85 "alice" 92 "bob" 78 "charlie" 95 "diana"
(integer) 4
127.0.0.1:6379> ZRANGEBYSCORE scores 80 90
1) "alice"
2) "charlie"

# ZREM and ZCARD
127.0.0.1:6379> ZREM leaderboard "player1"
(integer) 1
127.0.0.1:6379> ZCARD leaderboard
(integer) 2

8. BITMAP Operations

# SETBIT and GETBIT
127.0.0.1:6379> SETBIT user:online:20231201 1001 1  # User 1001 online
(integer) 0
127.0.0.1:6379> SETBIT user:online:20231201 1002 1  # User 1002 online
(integer) 0
127.0.0.1:6379> GETBIT user:online:20231201 1001
(integer) 1
127.0.0.1:6379> GETBIT user:online:20231201 999
(integer) 0

# BITCOUNT (count set bits)
127.0.0.1:6379> BITCOUNT user:online:20231201
(integer) 2

# BITOP (bitwise operations)
127.0.0.1:6379> SETBIT day1 1 1
(integer) 0
127.0.0.1:6379> SETBIT day1 3 1
(integer) 0
127.0.0.1:6379> SETBIT day2 2 1
(integer) 0
127.0.0.1:6379> SETBIT day2 3 1
(integer) 0
127.0.0.1:6379> BITOP OR weekly day1 day2
(integer) 1
127.0.0.1:6379> BITCOUNT weekly
(integer) 3

9. HYPERLOGLOG Operations

# PFADD and PFCOUNT
127.0.0.1:6379> PFADD visitors:page1 "user1" "user2" "user3" "user4"
(integer) 1
127.0.0.1:6379> PFADD visitors:page1 "user5" "user6"
(integer) 1
127.0.0.1:6379> PFCOUNT visitors:page1
(integer) 6

# PFMERGE (merge multiple HyperLogLogs)
127.0.0.1:6379> PFADD visitors:page2 "user1" "user7" "user8" "user9"
(integer) 1
127.0.0.1:6379> PFMERGE visitors:total visitors:page1 visitors:page2
OK
127.0.0.1:6379> PFCOUNT visitors:total
(integer) 9  # Approximate count

10. GEOSPATIAL Operations

# GEOADD and GEODIST
127.0.0.1:6379> GEOADD cities 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"
(integer) 2
127.0.0.1:6379> GEODIST cities Palermo Catania km
"166.2742"

# GEORADIUS (find within radius)
127.0.0.1:6379> GEOADD stores 13.583333 37.316667 "Store_A" 15.087269 37.502669 "Store_B"
(integer) 2
127.0.0.1:6379> GEORADIUS stores 13.5 37.3 200 km
1) "Store_A"

# GEOSEARCH (advanced geo queries)
127.0.0.1:6379> GEOADD locations -122.4194 37.7749 "San Francisco" -118.2437 34.0522 "Los Angeles"
(integer) 2
127.0.0.1:6379> GEOSEARCH locations FROMMEMBER "San Francisco" BYRADIUS 500 KM ASC
1) "San Francisco"
2) "Los Angeles"

11. STREAM Operations

# XADD and XRANGE
127.0.0.1:6379> XADD sensor_stream * temperature 23.5 humidity 60
"1640995200000-0"
127.0.0.1:6379> XADD sensor_stream * temperature 24.1 humidity 58
"1640995260000-0"
127.0.0.1:6379> XRANGE sensor_stream - +
1) 1) "1640995200000-0"
   2) 1) "temperature"
      2) "23.5"
      3) "humidity"
      4) "60"
2) 1) "1640995260000-0"
   2) 1) "temperature"
      2) "24.1"
      3) "humidity"
      4) "58"

# XGROUP and XREADGROUP
127.0.0.1:6379> XGROUP CREATE sensor_stream mygroup $ MKSTREAM
OK
127.0.0.1:6379> XREADGROUP GROUP mygroup consumer1 COUNT 1 STREAMS sensor_stream >
1) 1) "sensor_stream"
   2) 1) 1) "1640995200000-0"
         2) 1) "temperature"
            2) "23.5"
            3) "humidity"
            4) "60"

# XLEN and XTRIM
127.0.0.1:6379> XLEN sensor_stream
(integer) 2
127.0.0.1:6379> XTRIM sensor_stream MAXLEN 1  # Keep only latest entry
(integer) 1

12. TRANSACTIONS (MULTI/EXEC)

# MULTI/EXEC transaction
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> INCR counter
QUEUED
127.0.0.1:6379> LPUSH tasks "process_data"
QUEUED
127.0.0.1:6379> INCRBY points 100
QUEUED
127.0.0.1:6379> EXEC
1) (integer) 1
2) (integer) 1
3) (integer) 100

# DISCARD transaction
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET temp_key "value"
QUEUED
127.0.0.1:6379> DISCARD
OK

# WATCH for optimistic locking
127.0.0.1:6379> WATCH balance
OK
127.0.0.1:6379> GET balance
"100"
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> DECRBY balance 50
QUEUED
127.0.0.1:6379> EXEC
1) (integer) 50

13. PUBLISH/SUBSCRIBE (Pub/Sub)

# Terminal 1: Subscribe to channel
127.0.0.1:6379> SUBSCRIBE news sports
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "news"
3) (integer) 1
1) "subscribe"
2) "sports"
3) (integer) 2

# Terminal 2: Publish messages
127.0.0.1:6379> PUBLISH news "Breaking: Redis 7.0 released!"
(integer) 1
127.0.0.1:6379> PUBLISH sports "Team wins championship!"

# Pattern subscription
127.0.0.1:6379> PSUBSCRIBE news.*
1) "psubscribe"
2) "news.*"
3) (integer) 1

14. Lua Scripting

-- Simple Lua script: increment and get value
local current = redis.call('GET', KEYS[1])
if current == false then
    current = 0
else
    current = tonumber(current)
end
current = current + ARGV[1]
redis.call('SET', KEYS[1], current)
return current

-- Load and execute script
127.0.0.1:6379> EVAL "local current = redis.call('GET', KEYS[1]) if current == false then current = 0 else current = tonumber(current) end current = current + ARGV[1] redis.call('SET', KEYS[1], current) return current" 1 my_counter 5
(integer) 5

-- Using SCRIPT LOAD for reuse
127.0.0.1:6379> SCRIPT LOAD "return redis.call('GET', KEYS[1])"
"5332031c6b470dc5a0dd9b4bf2030dea6d65de91"
127.0.0.1:6379> EVALSHA 5332031c6b470dc5a0dd9b4bf2030dea6d65de91 1 mykey
"myvalue"

15. Persistence and Backup

# Save to disk (blocking)
127.0.0.1:6379> SAVE
OK

# Background save
127.0.0.1:6379> BGSAVE
Background saving started

# Last save time
127.0.0.1:6379> LASTSAVE
(integer) 1701427200

# Configure persistence
127.0.0.1:6379> CONFIG SET save "900 1 300 10 60 10000"
OK

# Append-only file (AOF)
127.0.0.1:6379> CONFIG SET appendonly yes
OK
127.0.0.1:6379> BGREWRITEAOF
Background append only file rewriting started

16. Performance and Monitoring

# Monitor commands in real-time
127.0.0.1:6379> MONITOR
OK
# Then run other commands to see them logged

# Slow log
127.0.0.1:6379> SLOWLOG GET 10
1) 1) (integer) 14
   2) (integer) 1640995200
   3) (integer) 10000
   4) 1) "KEYS"
      2) "*"
   5) "127.0.0.1:52342"
   6) "client_name"
   7) (empty array)

# Memory usage
127.0.0.1:6379> INFO memory
# Memory
used_memory:1024000
used_memory_human:1.00M
used_memory_rss:2048000
used_memory_peak:2048000

# Latency monitor
127.0.0.1:6379> CONFIG SET latency-monitor-threshold 100
OK
127.0.0.1:6379> LATENCY LATEST

17. Practical Application Examples

Session Management

# Store user session
127.0.0.1:6379> HMSET session:abc123 user_id 1000 username "john" created_at 1640995200
OK
127.0.0.1:6379> EXPIRE session:abc123 1800  # 30 minutes
(integer) 1

# Retrieve session
127.0.0.1:6379> HMGET session:abc123 user_id username
1) "1000"
2) "john"

Rate Limiting

# Sliding window rate limiter
127.0.0.1:6379> ZREMRANGEBYSCORE requests:user123 0 [current_timestamp - 60]
(integer) 2
127.0.0.1:6379> ZADD requests:user123 [current_timestamp] [current_timestamp]
(integer) 1
127.0.0.1:6379> ZCARD requests:user123
(integer) 3  # Number of requests in last minute

Leaderboard

# Update player score
127.0.0.1:6379> ZINCRBY game:leaderboard 150 "player1"
"150"

# Get top 10 players
127.0.0.1:6379> ZREVRANGE game:leaderboard 0 9 WITHSCORES

Cache with Expiration

# Cache expensive computation result
127.0.0.1:6379> SET cache:expensive_result "[JSON_RESULT]" EX 3600
OK

# Get cached result
127.0.0.1:6379> GET cache:expensive_result
"[JSON_RESULT]"

18. Bulk Operations and Pipelines

# Using pipelines for batch operations
127.0.0.1:6379> PIPELINE
127.0.0.1:6379> SET key1 "value1"
QUEUED
127.0.0.1:6379> SET key2 "value2"
QUEUED
127.0.0.1:6379> INCR counter
QUEUED
127.0.0.1:6379> EXEC
1) OK
2) OK
3) (integer) 1

# Using redis-cli with pipe
# echo -e "SET a 1\nSET b 2\nGET a" | redis-cli --pipe

19. Security and Access Control

# ACL basics
127.0.0.1:6379> ACL WHOAMI
"default"

# Create user with limited permissions
127.0.0.1:6379> ACL SETUSER readonly on >password123 ~cached:* +get +mget
OK

# Authenticate as user
127.0.0.1:6379> AUTH readonly password123
OK

20. Cluster and Replication (Basics)

# Check replication status
127.0.0.1:6379> INFO replication
# Replication
role:master
connected_slaves:1
slave0:ip=127.0.0.1,port=6380,state=online,offset=100,lag=1

# Cluster info
127.0.0.1:6379> CLUSTER INFO
cluster_state:ok
cluster_size:3

Complete Demo Script

#!/bin/bash
# redis_demo.sh - Complete Redis demonstration

echo "=== Redis Command Demo ==="

# Connect and test
redis-cli << EOF
PING
SELECT 1
FLUSHDB
EOF

echo "1. STRING Operations:"
redis-cli << EOF
SET name "Redis Demo"
GET name
INCR counter
INCRBY counter 10
APPEND name " - Extended"
GET name
EOF

echo "2. HASH Operations:"
redis-cli << EOF
HMSET user:1 name "Alice" age "25" city "London"
HGETALL user:1
HINCRBY user:1 age 1
HGET user:1 age
EOF

echo "3. LIST Operations:"
redis-cli << EOF
LPUSH tasks "clean" "code" "test"
RPUSH tasks "deploy"
LRANGE tasks 0 -1
EOF

echo "4. SET Operations:"
redis-cli << EOF
SADD technologies "Redis" "MongoDB" "PostgreSQL"
SMEMBERS technologies
SISMEMBER technologies "Redis"
EOF

echo "5. SORTED SET Operations:"
redis-cli << EOF
ZADD scores 85 "Alice" 92 "Bob" 78 "Charlie"
ZREVRANGE scores 0 -1 WITHSCORES
EOF

echo "6. Transaction Example:"
redis-cli << EOF
MULTI
INCR transaction_test
LPUSH items "item1"
EXEC
EOF

echo "Demo completed! All operations executed successfully."

This comprehensive Redis command demo covers all major data types and operations you'd typically use in real-world applications, from basic CRUD operations to advanced features like transactions, pub/sub, and Lua scripting.

 

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐