Site logo
Tác giả
  • avatar Nguyễn Đức Xinh
    Name
    Nguyễn Đức Xinh
    Twitter
Ngày xuất bản
Ngày xuất bản

Redis Commands: Hướng dẫn chi tiết các lệnh Redis phổ biến và cách sử dụng

Redis Commands và Redis CLI

Redis CLI (Command Line Interface) là công cụ mạnh mẽ để tương tác với Redis server, thực hiện operations, monitoring, và troubleshooting. Trong bài viết này, chúng ta sẽ đi sâu vào các lệnh Redis phổ biến, cách kết nối, và các kỹ thuật để làm việc hiệu quả với Redis.

Kết nối đến Redis Server

Cách kết nối cơ bản

Redis CLI cung cấp nhiều options để kết nối đến Redis server:

# Kết nối đến localhost (mặc định)
redis-cli

# Kết nối đến remote host
redis-cli -h <hostname>

# Kết nối với port cụ thể
redis-cli -h <hostname> -p <port>

# Ví dụ kết nối đến localhost port 6379
redis-cli -h localhost -p 6379

# Kết nối đến specific database (mặc định là db 0)
redis-cli -h localhost -n 1

Kết nối đến Azure Redis Cache

Azure Redis Cache có format hostname đặc biệt:

# Format: <name>.redis.cache.windows.net
redis-cli -h xxx.redis.cache.windows.net -p 6379

# Ví dụ cụ thể
redis-cli -h prod-myapp.redis.cache.windows.net -p 6380

# SSL connection (Azure Redis thường yêu cầu SSL trên port 6380)
redis-cli -h prod-myapp.redis.cache.windows.net -p 6380 --tls

Kết nối đến AWS ElastiCache

# AWS ElastiCache primary endpoint
redis-cli -h myapp.abcdef.0001.use1.cache.amazonaws.com -p 6379

# ElastiCache với encryption in-transit
redis-cli -h myapp.abcdef.ng.0001.use1.cache.amazonaws.com -p 6379 --tls

Authentication trong Redis

Cách 1: Authentication sau khi kết nối

# Kết nối trước
redis-cli -h <hostname> -p 6379

# Authenticate sau khi vào CLI
AUTH <password>

# Với Redis 6.0+ có ACL (Access Control Lists)
AUTH <username> <password>

# Ví dụ
AUTH default your_strong_password
# Response: OK

Cách 2: Authentication khi kết nối

# Sử dụng flag -a (không an toàn vì password visible trong history)
redis-cli -h <hostname> -p 6379 -a your_password

# ⚠️ Warning: Using a password on the command line interface is insecure.
# Đọc password securely (không hiển thị khi gõ)
read -s REDIS_PASS
# Gõ password và Enter

# Sử dụng password từ environment variable
redis-cli -h prod-myapp.redis.cache.windows.net -p 6379 -a "$REDIS_PASS"

# Hoặc export environment variable
export REDIS_PASSWORD="your_password"
redis-cli -h hostname -p 6379 -a "$REDIS_PASSWORD"

Cách 4: Sử dụng REDISCLI_AUTH environment variable

# Set environment variable (Redis CLI tự động sử dụng)
export REDISCLI_AUTH="your_password"

# Kết nối mà không cần -a flag
redis-cli -h hostname -p 6379

# Password sẽ được tự động authenticate

Redis 6.0+ ACL (Access Control Lists)

Redis 6.0 giới thiệu ACL để quản lý users và permissions chi tiết:

# Liệt kê users
ACL LIST

# Thông tin về current user
ACL WHOAMI

# Tạo user mới với specific permissions
ACL SETUSER analyst on >password123 ~cached:* +get +ttl

# Authenticate với specific user
AUTH analyst password123

# Xem permissions của user hiện tại
ACL GETUSER analyst

INFO Commands - Monitoring Redis

INFO REPLICATION - Kiểm tra Replication Status

Lệnh này cực kỳ quan trọng để kiểm tra high availability setup:

INFO replication

Output ví dụ cho Master:

# Replication
role:master
connected_slaves:2
slave0:ip=10.0.1.10,port=6379,state=online,offset=123456,lag=0
slave1:ip=10.0.1.11,port=6379,state=online,offset=123456,lag=0
master_replid:8c72408dad4fdcb9da02ef84461b04db76df854b
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:123456
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:123456

Output ví dụ cho Slave/Replica:

# Replication
role:slave
master_host:10.0.1.5
master_port:6379
master_link_status:up
master_last_io_seconds_ago:0
master_sync_in_progress:0
slave_repl_offset:123456
slave_priority:100
slave_read_only:1
connected_slaves:0

Giải thích các fields quan trọng:

Field Ý nghĩa Quan trọng
role master hoặc slave/replica Xác định vai trò của instance
connected_slaves Số lượng slaves connected Monitor replication health
master_link_status up/down (trên slave) Kiểm tra connection đến master
master_last_io_seconds_ago Giây kể từ I/O cuối Detect replication lag
slave_repl_offset Offset của slave So sánh với master offset
master_repl_offset Current offset của master Track replication progress
lag Độ trễ replication (giây) Performance indicator

Use cases:

# Script kiểm tra replication health
redis-cli INFO replication | grep role
# Output: role:master

# Kiểm tra slave lag
redis-cli INFO replication | grep lag
# Output: slave0:...,lag=0

# Alert nếu slave disconnected
SLAVE_COUNT=$(redis-cli INFO replication | grep connected_slaves | cut -d: -f2)
if [ $SLAVE_COUNT -lt 2 ]; then
    echo "WARNING: Expected 2 slaves, found $SLAVE_COUNT"
fi

INFO SERVER - Thông tin Server

INFO server

Output ví dụ:

# Server
redis_version:6.0.14
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:abc123def456
redis_mode:standalone
os:Windows
arch_bits:64
multiplexing_api:winsock_IOCP
atomicvar_api:pthread-mutex
gcc_version:7.4.0
process_id:12345
run_id:8c72408dad4fdcb9da02ef84461b04db76df854b
tcp_port:6379
uptime_in_seconds:2908
uptime_in_days:0
hz:10
configured_hz:10
lru_clock:15234567

Giải thích chi tiết:

Field Ý nghĩa Use Case
redis_version Version của Redis đang chạy Compatibility check, security updates
redis_mode standalone, sentinel, hoặc cluster Architecture verification
os Operating system Platform-specific optimizations
arch_bits 32-bit hoặc 64-bit Memory limitations (32-bit limited to 4GB)
multiplexing_api I/O multiplexing method Performance tuning (epoll, kqueue, etc.)
process_id PID của Redis process System monitoring, debugging
run_id Unique ID của Redis instance Identify restarts
tcp_port Port đang listen Connection configuration
uptime_in_seconds Thời gian running Stability monitoring
uptime_in_days Uptime theo ngày Quick uptime check
hz Server frequency Background tasks frequency

Ví dụ sử dụng:

# Check Redis version
redis-cli INFO server | grep redis_version
# Output: redis_version:6.0.14

# Kiểm tra uptime
redis-cli INFO server | grep uptime_in_days
# Output: uptime_in_days:45

# Verify mode (standalone/cluster)
redis-cli INFO server | grep redis_mode
# Output: redis_mode:cluster

# Check process ID
redis-cli INFO server | grep process_id
# Output: process_id:12345

# Monitor cho restart (run_id changes khi restart)
CURRENT_RUN_ID=$(redis-cli INFO server | grep run_id | cut -d: -f2)
echo "Current run_id: $CURRENT_RUN_ID"

INFO STATS - Statistics và Performance Metrics

INFO stats

Output ví dụ:

# Stats
total_connections_received:93068
total_commands_processed:427242
instantaneous_ops_per_sec:90
instantaneous_input_kbps:24.52
instantaneous_output_kbps:3.60
rejected_connections:0
sync_full:0
sync_partial_ok:0
sync_partial_err:0
expired_keys:2213
expired_stale_perc:0.00
expired_time_cap_reached_count:0
evicted_keys:0
keyspace_hits:75771
keyspace_misses:53415
pubsub_channels:0
pubsub_patterns:0
latest_fork_usec:1234
migrate_cached_sockets:0
slave_expires_tracked_keys:0
active_defrag_hits:0
active_defrag_misses:0
active_defrag_key_hits:0
active_defrag_key_misses:0

Giải thích metrics quan trọng:

Connection Metrics

Metric Ý nghĩa Good/Bad Indicator
total_connections_received Tổng số connections từ khi start Historical data
rejected_connections Connections bị reject ⚠️ Nên là 0
instantaneous_ops_per_sec Operations/giây hiện tại Performance indicator
# Monitor rejected connections (cảnh báo nếu > 0)
REJECTED=$(redis-cli INFO stats | grep rejected_connections | cut -d: -f2)
if [ $REJECTED -gt 0 ]; then
    echo "WARNING: $REJECTED connections rejected. Check maxclients setting."
fi

Performance Metrics

Metric Ý nghĩa Interpretation
instantaneous_ops_per_sec Ops/giây real-time Load indicator
instantaneous_input_kbps KB/s input traffic Network bandwidth usage
instantaneous_output_kbps KB/s output traffic Network bandwidth usage
# Monitor operations per second
watch -n 1 'redis-cli INFO stats | grep instantaneous_ops_per_sec'

# Check if near capacity (assuming max 100k ops/sec)
OPS=$(redis-cli INFO stats | grep instantaneous_ops_per_sec | cut -d: -f2)
if [ $OPS -gt 80000 ]; then
    echo "WARNING: High load - $OPS ops/sec"
fi

Cache Efficiency Metrics

Metric Ý nghĩa Formula
keyspace_hits Số lần tìm thấy key Cache hit
keyspace_misses Số lần không tìm thấy key Cache miss
Hit Rate Tỷ lệ cache hit hits / (hits + misses) * 100%
# Tính cache hit rate
HITS=$(redis-cli INFO stats | grep keyspace_hits | cut -d: -f2)
MISSES=$(redis-cli INFO stats | grep keyspace_misses | cut -d: -f2)
TOTAL=$((HITS + MISSES))
HIT_RATE=$(echo "scale=2; $HITS * 100 / $TOTAL" | bc)

echo "Cache Hit Rate: $HIT_RATE%"
# Good: > 80%, Warning: < 60%, Critical: < 40%

if (( $(echo "$HIT_RATE < 60" | bc -l) )); then
    echo "⚠️ Low cache hit rate! Consider:"
    echo "  - Increasing cache TTL"
    echo "  - Pre-warming cache"
    echo "  - Reviewing caching strategy"
fi

Memory Eviction Metrics

Metric Ý nghĩa Action
expired_keys Keys expired tự nhiên Normal behavior
evicted_keys Keys bị evict do memory pressure ⚠️ Cần tăng memory
# Kiểm tra eviction
EVICTED=$(redis-cli INFO stats | grep evicted_keys | cut -d: -f2)
if [ $EVICTED -gt 0 ]; then
    echo "⚠️ WARNING: $EVICTED keys evicted"
    echo "Memory pressure detected. Actions:"
    echo "  1. Increase maxmemory"
    echo "  2. Review eviction policy"
    echo "  3. Optimize data structures"
fi

INFO MEMORY - Memory Usage

INFO memory

Key metrics:

# Memory
used_memory:1048576
used_memory_human:1.00M
used_memory_rss:2097152
used_memory_rss_human:2.00M
used_memory_peak:3145728
used_memory_peak_human:3.00M
maxmemory:10485760
maxmemory_human:10.00M
maxmemory_policy:allkeys-lru
mem_fragmentation_ratio:2.00

Giải thích:

Metric Ý nghĩa Healthy Range
used_memory Memory sử dụng bởi Redis < 80% maxmemory
used_memory_rss Resident Set Size (OS allocated) Close to used_memory
used_memory_peak Peak memory usage Track growth
maxmemory Max memory limit Set appropriately
mem_fragmentation_ratio RSS / used_memory 1.0 - 1.5
# Check memory usage percentage
USED=$(redis-cli INFO memory | grep used_memory: | head -1 | cut -d: -f2)
MAX=$(redis-cli INFO memory | grep maxmemory: | head -1 | cut -d: -f2)
PERCENT=$(echo "scale=2; $USED * 100 / $MAX" | bc)

echo "Memory Usage: $PERCENT%"
if (( $(echo "$PERCENT > 80" | bc -l) )); then
    echo "⚠️ High memory usage!"
fi

INFO CLIENTS - Client Connections

INFO clients

Output:

# Clients
connected_clients:42
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:5

Monitoring script:

# Alert if too many connections
MAX_CLIENTS=1000
CONNECTED=$(redis-cli INFO clients | grep connected_clients | cut -d: -f2)

if [ $CONNECTED -gt $MAX_CLIENTS ]; then
    echo "⚠️ High number of connections: $CONNECTED"
fi

# Check blocked clients (waiting on BLPOP, BRPOP, etc.)
BLOCKED=$(redis-cli INFO clients | grep blocked_clients | cut -d: -f2)
echo "Blocked clients: $BLOCKED"

Common Redis Commands

Key Management Commands

EXISTS - Kiểm tra key tồn tại

# Kiểm tra single key
EXISTS mykey
# Returns: 1 (exists) or 0 (not exists)

# Kiểm tra multiple keys
EXISTS key1 key2 key3
# Returns: số lượng keys tồn tại (0-3)

DEL - Xóa keys

# Xóa single key
DEL mykey
# Returns: 1 (deleted) or 0 (key not found)

# Xóa multiple keys
DEL key1 key2 key3
# Returns: số lượng keys đã xóa

# Xóa với pattern matching (dangerous!)
redis-cli KEYS "temp:*" | xargs redis-cli DEL

TTL - Time To Live

# Kiểm tra TTL (seconds)
TTL mykey
# Returns: 
#   positive number: seconds remaining
#   -1: key exists but no expiration
#   -2: key does not exist

# Kiểm tra TTL (milliseconds)
PTTL mykey

# Set expiration
EXPIRE mykey 3600  # expire sau 1 giờ
EXPIREAT mykey 1640995200  # expire tại timestamp cụ thể

# Remove expiration
PERSIST mykey

TYPE - Xem data type

TYPE mykey
# Returns: string, list, set, zset, hash, stream, none

KEYS - List keys (⚠️ Use carefully in production)

# List all keys (DANGEROUS on large databases)
KEYS *

# Pattern matching
KEYS user:*
KEYS session:*:profile
KEYS cache:product:*

# ⚠️ KEYS blocks server - use SCAN instead in production
# Scan với cursor
SCAN 0 MATCH user:* COUNT 100

# Returns: [new_cursor, [keys]]
# Example: ["17", ["user:1", "user:2", "user:3"]]

# Iterate cho đến khi cursor = 0
cursor=0
while true; do
    result=$(redis-cli SCAN $cursor MATCH "user:*" COUNT 100)
    cursor=$(echo $result | awk '{print $1}')
    # Process keys...
    if [ $cursor -eq 0 ]; then
        break
    fi
done

RENAME - Đổi tên key

# Rename key
RENAME oldkey newkey

# Rename chỉ khi newkey chưa tồn tại
RENAMENX oldkey newkey
# Returns: 1 (success) or 0 (newkey exists)

String Commands

# SET với options
SET key value
SET key value EX 3600  # Expire sau 3600 seconds
SET key value PX 3600000  # Expire sau 3600000 milliseconds
SET key value NX  # Chỉ set nếu key chưa tồn tại
SET key value XX  # Chỉ set nếu key đã tồn tại

# GET
GET key

# MSET/MGET - Multiple keys
MSET key1 value1 key2 value2 key3 value3
MGET key1 key2 key3

# INCR/DECR - Atomic increment/decrement
INCR counter
INCRBY counter 5
DECR counter
DECRBY counter 3

# String operations
APPEND key " additional text"
STRLEN key
GETRANGE key 0 10
SETRANGE key 5 "NEW"

Hash Commands

# HSET/HGET
HSET user:1000 name "John Doe"
HSET user:1000 email "john@example.com" age 30
HGET user:1000 name

# HMSET/HMGET - Multiple fields
HMSET user:1001 name "Jane" email "jane@example.com" age 28
HMGET user:1001 name email

# HGETALL - Get all fields
HGETALL user:1000

# HDEL - Delete fields
HDEL user:1000 age

# HEXISTS - Check field exists
HEXISTS user:1000 email

# HKEYS/HVALS
HKEYS user:1000  # Get all field names
HVALS user:1000  # Get all values

# HLEN
HLEN user:1000  # Number of fields

# HINCRBY
HINCRBY user:1000 age 1
HINCRBYFLOAT user:1000 balance 10.50

List Commands

# LPUSH/RPUSH - Add to list
LPUSH mylist "first"  # Add to head
RPUSH mylist "last"   # Add to tail
LPUSH mylist value1 value2 value3

# LPOP/RPOP - Remove from list
LPOP mylist  # Remove from head
RPOP mylist  # Remove from tail

# BLPOP/BRPOP - Blocking pop (for queues)
BLPOP mylist 10  # Block up to 10 seconds
BRPOP mylist 0   # Block indefinitely

# LRANGE - Get range
LRANGE mylist 0 -1   # Get all items
LRANGE mylist 0 9    # Get first 10 items

# LLEN - List length
LLEN mylist

# LINDEX - Get item at index
LINDEX mylist 0

# LSET - Set item at index
LSET mylist 0 "new value"

# LTRIM - Trim list to range
LTRIM mylist 0 99  # Keep first 100 items

Set Commands

# SADD - Add members
SADD myset member1 member2 member3

# SMEMBERS - Get all members
SMEMBERS myset

# SISMEMBER - Check membership
SISMEMBER myset member1
# Returns: 1 (member) or 0 (not member)

# SREM - Remove members
SREM myset member1

# SCARD - Set cardinality (count)
SCARD myset

# Set operations
SINTER set1 set2  # Intersection
SUNION set1 set2  # Union
SDIFF set1 set2   # Difference

# SPOP - Remove random member
SPOP myset
SPOP myset 3  # Remove 3 random members

# SRANDMEMBER - Get random member without removing
SRANDMEMBER myset
SRANDMEMBER myset 5  # Get 5 random members

Sorted Set Commands

# ZADD - Add members with scores
ZADD leaderboard 100 "player1"
ZADD leaderboard 250 "player2" 175 "player3"

# ZRANGE - Get range (by index)
ZRANGE leaderboard 0 -1  # All members, ascending
ZRANGE leaderboard 0 9 WITHSCORES  # Top 10 with scores

# ZREVRANGE - Reverse range (descending)
ZREVRANGE leaderboard 0 9 WITHSCORES  # Top 10 highest scores

# ZRANK - Get rank (0-based index)
ZRANK leaderboard "player1"
ZREVRANK leaderboard "player1"  # Rank in descending order

# ZSCORE - Get score
ZSCORE leaderboard "player1"

# ZINCRBY - Increment score
ZINCRBY leaderboard 10 "player1"

# ZREM - Remove members
ZREM leaderboard "player1"

# ZCARD - Count members
ZCARD leaderboard

# ZCOUNT - Count members in score range
ZCOUNT leaderboard 100 200

# ZRANGEBYSCORE - Get by score range
ZRANGEBYSCORE leaderboard 100 200 WITHSCORES
ZRANGEBYSCORE leaderboard -inf +inf LIMIT 0 10

Database Management Commands

SELECT - Switch database

# Redis có 16 databases mặc định (0-15)
SELECT 0  # Switch to database 0
SELECT 1  # Switch to database 1

FLUSHDB / FLUSHALL - Clear data

# ⚠️ DANGEROUS COMMANDS

# Xóa tất cả keys trong current database
FLUSHDB

# Xóa tất cả keys trong TẤT CẢ databases
FLUSHALL

# Async versions (recommended)
FLUSHDB ASYNC
FLUSHALL ASYNC

DBSIZE - Count keys

# Đếm số lượng keys trong current database
DBSIZE

SAVE / BGSAVE - Create snapshot

# Synchronous save (blocks server)
SAVE

# Background save (recommended)
BGSAVE

# Check if save is in progress
LASTSAVE  # Returns timestamp of last successful save

Advanced Commands

MONITOR - Real-time command monitoring

# Monitor tất cả commands real-time (⚠️ impacts performance)
MONITOR

# Output example:
# 1614556800.123456 [0 127.0.0.1:6379] "SET" "key" "value"
# 1614556801.234567 [0 127.0.0.1:6379] "GET" "key"

# ⚠️ Chỉ dùng cho debugging, không dùng trên production!

SLOWLOG - Query slow commands

# Get slow commands
SLOWLOG GET 10  # Get 10 slowest commands

# Get slowlog length
SLOWLOG LEN

# Reset slowlog
SLOWLOG RESET

# Configure slow log threshold (microseconds)
CONFIG SET slowlog-log-slower-than 10000  # 10ms

CLIENT LIST - List connected clients

# List all connected clients
CLIENT LIST

# Output example:
# id=123 addr=127.0.0.1:52698 fd=8 name= age=3 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 obl=0 oll=0 omem=0 events=r cmd=client

# Kill specific client
CLIENT KILL 127.0.0.1:52698

# Set client name (helpful for debugging)
CLIENT SETNAME myapp-worker-1
CLIENT GETNAME

CONFIG - Runtime configuration

# Get configuration
CONFIG GET maxmemory
CONFIG GET *  # Get all configurations

# Set configuration (runtime, không persistent)
CONFIG SET maxmemory 2gb
CONFIG SET maxclients 10000

# Rewrite config file
CONFIG REWRITE

# Reset stats
CONFIG RESETSTAT

Troubleshooting Commands

1. Kiểm tra DNS và Network Connectivity

# Kiểm tra DNS resolution
nslookup redis.domain.com
nslookup prod-myapp.redis.cache.windows.net

# Kiểm tra DNS cache (trên client machine)
# Windows
ipconfig /displaydns
ipconfig /flushdns

# Linux/macOS
sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder

# Test connection với telnet
telnet redis.domain.com 6379

# Test connection với nc (netcat)
nc -zv redis.domain.com 6379

# Test với timeout
timeout 5 redis-cli -h redis.domain.com -p 6379 PING

2. Network Latency Testing

# Ping Redis server
redis-cli -h hostname -p 6379 PING
# Expected: PONG

# Measure latency
redis-cli -h hostname -p 6379 --latency
# Output: min: 0, max: 1, avg: 0.25 (1234 samples)

# Latency histogram
redis-cli -h hostname -p 6379 --latency-history

# Intrinsic latency (baseline)
redis-cli -h hostname -p 6379 --intrinsic-latency 100

3. Memory Issues

# Check memory usage
redis-cli INFO memory

# Find biggest keys
redis-cli --bigkeys

# Sample keys with memory usage
redis-cli --memkeys

# Check specific key memory
MEMORY USAGE keyname

# Analyze memory
MEMORY DOCTOR
MEMORY STATS

4. Performance Issues

# Check slow queries
redis-cli SLOWLOG GET 50

# Monitor commands real-time
redis-cli MONITOR

# Check command stats
redis-cli INFO commandstats

# Output example:
# cmdstat_get:calls=12345,usec=123456,usec_per_call=10.00
# cmdstat_set:calls=23456,usec=234567,usec_per_call=10.00

# Identify expensive commands
redis-cli INFO commandstats | grep usec_per_call | sort -t= -k3 -n -r

5. Connection Issues

# Check current connections
redis-cli INFO clients

# Check max clients setting
redis-cli CONFIG GET maxclients

# List all connected clients
redis-cli CLIENT LIST

# Kill idle connections
redis-cli CLIENT LIST | grep idle=300 | awk '{print $2}' | cut -d= -f2 | xargs -I {} redis-cli CLIENT KILL ADDR {}

# Set connection timeout
redis-cli CONFIG SET timeout 300  # Close idle connections after 300 seconds

6. Replication Issues

# Check replication status
redis-cli INFO replication

# Check replication lag
redis-cli INFO replication | grep lag

# Force resync (on slave)
redis-cli SLAVEOF NO ONE  # Promote to master temporarily
redis-cli SLAVEOF master-ip 6379  # Re-establish replication

# Check replication backlog
redis-cli CONFIG GET repl-backlog-size

So sánh Redis CLI với các công cụ khác

Redis CLI vs RedisInsight (GUI)

Feature Redis CLI RedisInsight
Interface Command line Graphical UI
Speed Very fast Slower
Scriptable Dễ dàng script Limited
Visualization Text only Charts, graphs
Memory Analysis Manual Visual analysis
Learning Curve Steep Easy
Best For Automation, scripting, production Development, debugging
Performance Impact Minimal Moderate

Redis CLI vs redis-py (Python Client)

Aspect Redis CLI redis-py
Purpose Interactive, admin Programmatic access
Use Case Debugging, monitoring Application integration
Pipelining Manual Built-in
Connection Pooling N/A Built-in
Error Handling Manual Automatic
Best For Quick tasks Production apps

Redis CLI vs Medis/AnotherRedisDesktopManager

Feature Redis CLI GUI Tools
Setup None Installation required
Remote Access SSH + CLI Direct connection
Bulk Operations Scriptable Click-based
Filtering grep, awk Built-in search
Production Use ✅ Recommended ⚠️ Use carefully

Practical Scripts và Use Cases

Script 1: Health Check

#!/bin/bash
# redis-health-check.sh

REDIS_HOST="localhost"
REDIS_PORT="6379"
REDIS_PASSWORD="your_password"

echo "=== Redis Health Check ==="

# Test connectivity
echo -n "Connectivity: "
if redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" PING > /dev/null 2>&1; then
    echo "✅ OK"
else
    echo "❌ FAILED"
    exit 1
fi

# Check memory usage
MEMORY_USED=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" INFO memory | grep used_memory_human | cut -d: -f2 | tr -d '\r')
echo "Memory Used: $MEMORY_USED"

# Check connected clients
CLIENTS=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" INFO clients | grep connected_clients | cut -d: -f2 | tr -d '\r')
echo "Connected Clients: $CLIENTS"

# Check ops/sec
OPS=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" INFO stats | grep instantaneous_ops_per_sec | cut -d: -f2 | tr -d '\r')
echo "Ops/sec: $OPS"

# Check cache hit rate
HITS=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" INFO stats | grep keyspace_hits | cut -d: -f2 | tr -d '\r')
MISSES=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" INFO stats | grep keyspace_misses | cut -d: -f2 | tr -d '\r')
TOTAL=$((HITS + MISSES))
if [ $TOTAL -gt 0 ]; then
    HIT_RATE=$(echo "scale=2; $HITS * 100 / $TOTAL" | bc)
    echo "Cache Hit Rate: $HIT_RATE%"
fi

# Check replication
ROLE=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" INFO replication | grep role | cut -d: -f2 | tr -d '\r')
echo "Role: $ROLE"

echo "=== Health Check Complete ==="

Script 2: Backup Database

#!/bin/bash
# redis-backup.sh

REDIS_HOST="localhost"
REDIS_PORT="6379"
REDIS_PASSWORD="your_password"
BACKUP_DIR="/backups/redis"
DATE=$(date +%Y%m%d_%H%M%S)

echo "Starting Redis backup..."

# Trigger BGSAVE
redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" BGSAVE > /dev/null

# Wait for save to complete
while true; do
    SAVE_IN_PROGRESS=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" INFO persistence | grep rdb_bgsave_in_progress | cut -d: -f2 | tr -d '\r')
    if [ "$SAVE_IN_PROGRESS" == "0" ]; then
        break
    fi
    echo "Waiting for backup to complete..."
    sleep 1
done

# Copy RDB file
RDB_FILE="/var/lib/redis/dump.rdb"
BACKUP_FILE="$BACKUP_DIR/dump_$DATE.rdb"

cp $RDB_FILE $BACKUP_FILE
gzip $BACKUP_FILE

echo "Backup completed: $BACKUP_FILE.gz"

# Cleanup old backups (keep last 7 days)
find $BACKUP_DIR -name "dump_*.rdb.gz" -mtime +7 -delete

Script 3: Monitor Cache Hit Rate

#!/bin/bash
# monitor-hit-rate.sh

REDIS_HOST="localhost"
REDIS_PORT="6379"
REDIS_PASSWORD="your_password"

while true; do
    HITS=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" INFO stats | grep keyspace_hits: | cut -d: -f2 | tr -d '\r')
    MISSES=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" INFO stats | grep keyspace_misses: | cut -d: -f2 | tr -d '\r')
    TOTAL=$((HITS + MISSES))
    
    if [ $TOTAL -gt 0 ]; then
        HIT_RATE=$(echo "scale=2; $HITS * 100 / $TOTAL" | bc)
        TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
        
        echo "$TIMESTAMP - Hit Rate: $HIT_RATE% (Hits: $HITS, Misses: $MISSES)"
        
        # Alert if hit rate too low
        if (( $(echo "$HIT_RATE < 70" | bc -l) )); then
            echo "⚠️ WARNING: Low hit rate detected!"
        fi
    fi
    
    sleep 60
done

Script 4: Find Large Keys

#!/bin/bash
# find-large-keys.sh

REDIS_HOST="localhost"
REDIS_PORT="6379"
REDIS_PASSWORD="your_password"
THRESHOLD_MB=1

echo "Searching for keys larger than ${THRESHOLD_MB}MB..."

# Get sample of keys
redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" --scan | while read key; do
    # Get memory usage
    MEMORY=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" MEMORY USAGE "$key")
    
    if [ ! -z "$MEMORY" ]; then
        MEMORY_MB=$(echo "scale=2; $MEMORY / 1024 / 1024" | bc)
        
        # Check if above threshold
        if (( $(echo "$MEMORY_MB > $THRESHOLD_MB" | bc -l) )); then
            TYPE=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" TYPE "$key")
            echo "Key: $key | Type: $TYPE | Size: ${MEMORY_MB}MB"
        fi
    fi
done

Best Practices khi sử dụng Redis CLI

1. Production Safety

# ✅ DO: Use --no-auth-warning để tránh warning trong logs
redis-cli -h hostname -a "$REDIS_PASSWORD" --no-auth-warning PING

# ✅ DO: Set timeout để tránh hang
redis-cli -h hostname --connect-timeout 5 --timeout 3 PING

# ❌ DON'T: Sử dụng KEYS * trên production
redis-cli KEYS *  # Blocks entire server!

# ✅ DO: Sử dụng SCAN thay thế
redis-cli --scan --pattern "user:*"

# ❌ DON'T: Run MONITOR trên production
redis-cli MONITOR  # Impacts performance

# ✅ DO: Use SLOWLOG thay thế
redis-cli SLOWLOG GET 10

2. Automation và Scripting

# Pipeline commands từ file
cat commands.txt | redis-cli -h hostname -a "$REDIS_PASSWORD"

# Execute single command
redis-cli -h hostname -a "$REDIS_PASSWORD" GET mykey

# Execute multiple commands
redis-cli -h hostname -a "$REDIS_PASSWORD" <<EOF
SET key1 value1
SET key2 value2
GET key1
EOF

# Output to file
redis-cli -h hostname INFO > redis-info.txt

# CSV output
redis-cli --csv LRANGE mylist 0 -1

3. Security

# Sử dụng environment variables
export REDISCLI_AUTH="your_password"
redis-cli -h hostname PING

# Secure connection với TLS
redis-cli -h hostname --tls --cert client.crt --key client.key --cacert ca.crt

# Avoid password in command history
read -s REDIS_PASS
redis-cli -h hostname -a "$REDIS_PASS" PING

Kết luận

Redis CLI là công cụ mạnh mẽ và không thể thiếu cho việc quản lý, monitoring, và troubleshooting Redis. Hiểu rõ các commands và cách sử dụng chúng hiệu quả sẽ giúp bạn:

Key Takeaways

  1. Authentication - Luôn sử dụng secure methods để authenticate (environment variables, read -s)
  2. Monitoring - Sử dụng INFO commands để monitor health và performance
  3. Safety - Tránh dangerous commands trên production (KEYS *, MONITOR, FLUSHALL)
  4. Troubleshooting - Nắm vững workflow để diagnose issues nhanh chóng
  5. Automation - Script các tasks thường xuyên để tiết kiệm thời gian

Các bước tiếp theo

  1. ✅ Practice với các commands cơ bản trên local Redis
  2. ✅ Tạo monitoring scripts cho environment của bạn
  3. ✅ Setup alerting dựa trên metrics quan trọng
  4. ✅ Document Redis architecture và procedures
  5. ✅ Train team members về Redis best practices

Resources

  • Redis Commands Reference: https://redis.io/commands
  • Redis CLI Documentation: https://redis.io/topics/rediscli
  • Redis Administration: https://redis.io/topics/admin

Với kiến thức về Redis commands, bạn đã sẵn sàng để quản lý và troubleshoot Redis infrastructure một cách professional! 🚀