Redis on Linux: From Basics to Production-Ready Scripts
This guide covers Redis core data types (String, List, Hash, Set, Sorted Set) with practical Linux command examples, demonstrates building a message queue with List and storing user profiles with Hash, and provides production-ready shell scripts for backup, monitoring, and automated cleanup of idle keys, plus common pitfalls to avoid.
Redis Core Data Types
Redis is an in-memory key-value store where values can be rich data structures. The article explains five core types with a comparison table:
String – universal notepad; commands: SET, GET, INCR; use cases: login tokens, verification codes, article view counts.
List – pipeline conveyor; commands: LPUSH, RPOP; use case: simple message queue (e.g., async SMS after order).
Hash – electronic spreadsheet; commands: HMSET, HGET, HINCRBY; use case: user profiles with multiple fields.
Set – auto-deduplication tagger; commands: SADD, SINTER; use case: user tags (VIP, free), common friends.
Sorted Set – golden leaderboard; commands: ZADD, ZREVRANGE; use case: game power rankings, live gift leaderboards.
The author notes that 80% of daily work uses String and List; others can be referenced when needed.
Linux Hands-On Operations
Basic Operations: Login and String
Assuming Redis installed via yum install redis -y or apt install redis-server -y and started with systemctl start redis.
1. Login – Two methods:
# Method 1: one-time with password
redis-cli -h 127.0.0.1 -p 6379 -a your_password
# Prompt shows 127.0.0.1:6379>
# Method 2: passwordless for long-term (update config, restart)
sed -i 's/# requirepass foobared/requirepass your_password/' /etc/redis.conf
systemctl restart redis
# Then just `redis-cli`Warning: never expose passwords insecurely.
2. String Core Operations
# Store user login token with 2-hour expiry (EX seconds)
SET login:token:worker10086 "asdf1234ghjk" EX 7200
# Returns OK; auto-expires after 7200 seconds
# Check if user online
GET login:token:worker10086
# Increment article read count atomically (handles 100k concurrency)
INCR article:read:20251231
# Delete a key manually
DEL login:token:caught_slackingAdvanced Usage
1. List as Simple Message Queue – Scenario: user places order, send SMS asynchronously to avoid blocking.
# Producer (order service pushes task)
redis-cli LPUSH queue:sms_notify '{"msgId":"202501011200001","phone":"138****8888","orderId":"ORDER_123456","template":"payment_success","timestamp":1735708800}'
# Consumer (SMS service) - core logic shown
while true; do
# Blocking pop with 10s timeout
result=$(redis-cli BRPOP queue:sms_notify 10)
if [ -n "$result" ]; then
# Parse JSON (use jq in reality), send SMS
echo "Got task: $result"
# On failure, push to retry queue
# redis-cli LPUSH queue:sms_retry "$result"
else
echo "Queue empty, resting..."
fi
done2. Hash for User Profiles (Memory Efficient)
# Store all user info at once, key is user ID
# 1. Store with sensitive data masked/encrypted (done in app code)
redis-cli HMSET user:10086 \
name "老唐" \
age 28 \
phone_md5 "e10adc3949ba59abbe56e057f20f883e" \ # privacy
phone_preview "138****8888" \ # for display
last_login_ip "10.0.0.101" \
profile_json '{"vip_level": 3, "tags": ["摸鲜博主", "吃货"]}' \
continuous_checkin_days 0 # initial check-in days
# 2. Query only needed fields, avoid transmitting sensitive data
redis-cli HMGET user:10086 name phone_preview vip_level
# 3. Atomic update for high-frequency scenarios (daily check-in)
# Increment continuous check-in days
redis-cli HINCRBY user:10086 continuous_checkin_days 1
# Observe: last_checkin_date not defined yet, but HSET creates if missing, overwrites if exists
redis-cli HSET user:10086 last_checkin_date "2025-12-31"Operations Emergency Kit
1. Backup and Restore
# Background save, non-blocking
redis-cli bgsave
# Backup file typically at /var/lib/redis/dump.rdb
# Manual copy for safety
cp /var/lib/redis/dump.rdb /backup/redis_$(date +%Y%m%d).rdb
# If data accidentally deleted: stop, restore, fix permissions, restart
systemctl stop redis
cp /backup/redis_20251230.rdb /var/lib/redis/dump.rdb
chown redis:redis /var/lib/redis/dump.rdb
systemctl start redis2. Performance Monitoring Script
A bash script skeleton monitoring memory usage, client connections, and cleaning idle temporary keys.
#!/bin/bash
# monitor_redis.sh - simple monitoring script
REDIS_CMD="redis-cli"
THRESHOLD_MEM=85 # memory usage %
THRESHOLD_CONN=1000 # connection count
# 1. Check memory (parse info memory)
mem_info=$($REDIS_CMD info memory | grep -E "(used_memory_human|used_memory_peak_human)")
echo "Memory usage: $mem_info"
# In practice, parse numeric values and alert if over threshold
# 2. Check client connections
conn_count=$($REDIS_CMD info clients | grep connected_clients | cut -d: -f2)
if (( conn_count > THRESHOLD_CONN )); then
echo "Warning: current connections ($conn_count) too high!" # should trigger alert
fi
# 3. Auto-clean idle temporary keys (idle > 24h)
$REDIS_CMD SCAN 0 MATCH "tmp_cache:*" COUNT 50 | while read -r key; do
if [[ -n "$key" && "$key" != "0" ]]; then
idle_time=$($REDIS_CMD OBJECT IDLETIME "$key" 2>/dev/null)
if (( idle_time > 86400 )); then
echo "Cleaning idle key: $key (idle $idle_time seconds)"
$REDIS_CMD DEL "$key"
fi
fi
done3. Automated Cleanup + Backup (Retain 15 Days)
A complete bash script redis_clean_backup.sh that cleans idle keys matching patterns and performs backup with retention. Key features:
Configurable Redis host, port, password, DB, backup directory, retention days, key patterns to clean.
Safe integer parsing to avoid bash comparison errors (function to_integer).
Uses SCAN to iterate keys, checks OBJECT IDLETIME, deletes if idle exceeds threshold (default 15 days = 1,296,000 seconds).
Triggers BGSAVE, waits for completion (polling INFO persistence for rdb_bgsave_in_progress), copies RDB file to backup dir (fallback to --rdb if BGSAVE fails).
Removes backup files older than retention days using find -mtime +15.
Logs to file with timestamps (function log).
Full script provided in article with functions clean_idle_keys, auto_backup, main, and helper to_integer.
Usage Guide
Save script as redis_clean_backup.sh.
Edit config: Redis address, password, backup dir, etc.
Make executable: chmod +x redis_clean_backup.sh.
Test run: ./redis_clean_backup.sh.
Schedule via crontab (daily 2 AM):
0 2 * * * /path/to/redis_clean_backup.sh >> /var/log/redis_clean_backup.log 2>&1.
Key notes: adjust key prefixes per business; mount backup dir on separate disk; test in staging first.
Slacking Pitfall Guide (Lessons Learned)
Never use KEYS * on large datasets – blocks single-threaded Redis; use SCAN 0 MATCH user:* COUNT 100 for incremental scanning.
Don't expose passwords – store in config file (chmod 600) or environment variable ( REDIS_PWD=xxx redis-cli -a $REDIS_PWD).
Add random jitter to expiry – prevent cache avalanche: EX $((3600 + RANDOM%600)).
Choose persistence wisely – RDB for backup, AOF for durability; production recommends hybrid mode (configure in redis.conf).
Don't use LRANGE on large Lists – blocks; use LLEN for length, BRPOP / BLPOP for consumption.
Redis is not a lossless database – in the queue example, if consumer crashes after popping but before processing, task is lost. For critical tasks, use RPOPLPUSH to a backup list or switch to RabbitMQ/Kafka. Redis queues suit tolerable-loss scenarios (notifications, cache updates).
Conclusion: Redis is a super shortcut at your workstation. Used well, it turns tedious work into efficiency and overtime into slacking. The examples cover 80% of daily ops; copy-paste ready. Advanced topics (distributed locks, leaderboards) left for future.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Engineer Tang's Implementation Study Notes
Old Tang | Pseudo-full-stack tech player: writes code without going bald, manages projects without going crazy, delivers without staying up late. No formal tutorials here, only a "slacking-off" practical manual that cures system pain points. Focuses on Shell, SQL, Java, and delivery, turning complexity into simplicity and making efficiency fun.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
