Comprehensive Redis cheatsheet covering all data types (Strings, Lists, Sets, Hashes, Sorted Sets, Streams), commands, transactions, Lua scripting, Pub/Sub, replication, clustering, persistence, security, monitoring, and optimization. Perfect for developers and DB admins seeking a complete quick-reference guide.
- Introduction & Key Concepts
- Installation & Setup
- Basic Commands
- Strings
- Lists
- Sets
- Hashes
- Sorted Sets
- Bitmaps & HyperLogLog
- Geospatial
- Streams
- Keys & Expiration
- Transactions
- Lua Scripting
- Pub/Sub Messaging
- Redis Modules
- Persistence
- Replication & Sentinel
- Redis Cluster
- Performance Optimization
- Security
- Monitoring & Debugging
- Client Libraries
- In-memory data structure store
- Used as: Database, Cache, Message Broker
- Single-threaded (main operations) → Atomic by design
- Supports persistence (RDB snapshots + AOF logs)
- Replication (Master-Slave), Clustering (Sharding)
- Data types: String, List, Set, Hash, Sorted Set, Bitmap, HyperLogLog, Geospatial, Stream
Default ports: 6379 (non-TLS), 6380 (TLS)
sudo apt update
sudo apt install redis-server
sudo systemctl start redis-server
sudo systemctl enable redis-serverbrew install redis
brew services start redisdocker run --name redis -d -p 6379:6379 redis
docker exec -it redis redis-cliredis-cli -h 127.0.0.1 -p 6379 -a password
redis-cli --tls --cert client.crt --key client.key --cacert ca.crt| Command | Example | Description |
|---|---|---|
PING |
PING → PONG |
Check connection |
SELECT |
SELECT 0 |
Switch database (0-15) |
DBSIZE |
DBSIZE |
Number of keys |
FLUSHDB |
FLUSHDB |
Delete all keys in current DB |
FLUSHALL |
FLUSHALL |
Delete all keys in all DBs |
INFO |
INFO server |
Server stats/info |
CONFIG GET |
CONFIG GET maxmemory |
Get config value |
CONFIG SET |
CONFIG SET maxmemory 2gb |
Set config value |
MONITOR |
MONITOR |
Watch commands in real-time |
ECHO |
ECHO "hello" |
Print message |
Max size: 512 MB
| Command | Example | Description |
|---|---|---|
SET |
SET user:1 "John" |
Set value |
SETNX |
SETNX lock "1" |
Set if not exists |
SETEX |
SETEX session 60 "abc" |
Set with expiry (sec) |
PSETEX |
PSETEX session 60000 "abc" |
Set with expiry (ms) |
GET |
GET user:1 |
Get value |
GETSET |
GETSET counter 0 |
Get old, set new |
MSET |
MSET a 1 b 2 c 3 |
Set multiple |
MGET |
MGET a b c |
Get multiple |
INCR |
INCR counter |
Increment by 1 |
INCRBY |
INCRBY counter 10 |
Increment by N |
DECR |
DECR counter |
Decrement by 1 |
DECRBY |
DECRBY counter 5 |
Decrement by N |
INCRBYFLOAT |
INCRBYFLOAT price 1.99 |
Float increment |
APPEND |
APPEND message " world" |
Append to value |
STRLEN |
STRLEN user:1 |
Length of value |
SETRANGE |
SETRANGE key 5 "Redis" |
Overwrite at offset |
GETRANGE |
GETRANGE key 0 3 |
Substring |
Use cases: Caching, counters, session store, distributed locks
Ordered sequence (linked list). Operations on head/tail: O(1)
| Command | Example | Description |
|---|---|---|
LPUSH |
LPUSH queue "task1" |
Prepend |
RPUSH |
RPUSH queue "task1" |
Append |
LPOP |
LPOP queue |
Remove & return first |
RPOP |
RPOP queue |
Remove & return last |
LINDEX |
LINDEX queue 0 |
Get element at index |
LRANGE |
LRANGE queue 0 -1 |
Get range (0=first, -1=last) |
LLEN |
LLEN queue |
Length |
LREM |
LREM queue 2 "task1" |
Remove count occurrences |
LTRIM |
LTRIM queue 0 100 |
Keep range only |
LPUSHX |
LPUSHX queue "new" |
Prepend if exists |
RPUSHX |
RPUSHX queue "new" |
Append if exists |
LSET |
LSET queue 1 "new" |
Set at index |
LINSERT |
LINSERT queue BEFORE "task1" "new" |
Insert before/after |
RPOPLPUSH |
RPOPLPUSH queue1 queue2 |
Pop from one, push to another |
BLPOP |
BLPOP queue 10 |
Blocking left pop (timeout sec) |
BRPOP |
BRPOP queue 10 |
Blocking right pop |
BRPOPLPUSH |
BRPOPLPUSH queue1 queue2 10 |
Blocking version |
Use cases: Message queues, activity streams, history tracking
Unordered unique strings. Operations: O(1) for add/remove/check
| Command | Example | Description |
|---|---|---|
SADD |
SADD tags "redis" |
Add member(s) |
SREM |
SREM tags "redis" |
Remove member(s) |
SISMEMBER |
SISMEMBER tags "redis" |
Check existence |
SMEMBERS |
SMEMBERS tags |
Get all members |
SCARD |
SCARD tags |
Cardinality (size) |
SPOP |
SPOP tags 2 |
Remove & return random members |
SRANDMEMBER |
SRANDMEMBER tags 2 |
Get random members (no remove) |
SINTER |
SINTER set1 set2 |
Intersection |
SINTERSTORE |
SINTERSTORE dest set1 set2 |
Store intersection |
SUNION |
SUNION set1 set2 |
Union |
SUNIONSTORE |
SUNIONSTORE dest set1 set2 |
Store union |
SDIFF |
SDIFF set1 set2 |
Difference (set1 - set2) |
SDIFFSTORE |
SDIFFSTORE dest set1 set2 |
Store difference |
SMOVE |
SMOVE src dest "member" |
Move member |
SSCAN |
SSCALL tags 0 MATCH redis* |
Iterate (cursor-based) |
Use cases: Tags, unique visitors, relationships (friends, followers), set operations for analytics
Field-value pairs inside a key (like nested map)
| Command | Example | Description |
|---|---|---|
HSET |
HSET user:100 name "Alice" age 30 |
Set field(s) |
HSETNX |
HSETNX user:100 email "a@b.com" |
Set if field not exists |
HGET |
HGET user:100 name |
Get field |
HMGET |
HMGET user:100 name age |
Get multiple fields |
HGETALL |
HGETALL user:100 |
Get all fields & values |
HMSET |
HMSET user:100 name "Bob" age 25 |
Set multiple (deprecated, use HSET) |
HINCRBY |
HINCRBY user:100 age 1 |
Increment integer field |
HINCRBYFLOAT |
HINCRBYFLOAT acct:1 balance 10.5 |
Increment float |
HDEL |
HDEL user:100 age |
Delete field(s) |
HEXISTS |
HEXISTS user:100 name |
Check field existence |
HLEN |
HLEN user:100 |
Number of fields |
HKEYS |
HKEYS user:100 |
Get all field names |
HVALS |
HVALS user:100 |
Get all field values |
HSTRLEN |
HSTRLEN user:100 name |
Length of field's value |
HSCAN |
HSCAN user:100 0 MATCH name* |
Iterate fields |
Use cases: Storing objects (users, profiles, sessions), caching DB rows
Uniquelike Set but each member has a score → ordered by score
| Command | Example | Description |
|---|---|---|
ZADD |
ZADD leaderboard 100 "Alice" 95 "Bob" |
Add with scores |
ZADD (options) |
ZADD leaderboard NX 100 "Alice" |
NX (new only), XX (exists only), GT (greater than), LT (less than) |
ZRANGE |
ZRANGE leaderboard 0 -1 WITHSCORES |
By index (low to high) |
ZREVRANGE |
ZREVRANGE leaderboard 0 -1 WITHSCORES |
Reverse (high to low) |
ZRANGEBYSCORE |
ZRANGEBYSCORE leaderboard 80 100 WITHSCORES |
By score range |
ZREVRANGEBYSCORE |
ZREVRANGEBYSCORE leaderboard 100 80 |
Reverse by score |
ZSCORE |
ZSCORE leaderboard "Alice" |
Get score |
ZINCRBY |
ZINCRBY leaderboard 5 "Alice" |
Increment score |
ZRANK |
ZRANK leaderboard "Alice" |
Rank (lowest score) |
ZREVRANK |
ZREVRANK leaderboard "Alice" |
Rank (highest score) |
ZREM |
ZREM leaderboard "Bob" |
Remove member(s) |
ZCARD |
ZCARD leaderboard |
Count members |
ZCOUNT |
ZCOUNT leaderboard 80 100 |
Count by score range |
ZREMRANGEBYRANK |
ZREMRANGEBYRANK leaderboard 0 10 |
Remove by rank |
ZREMRANGEBYSCORE |
ZREMRANGEBYSCORE leaderboard 0 50 |
Remove by score |
ZUNIONSTORE |
ZUNIONSTORE out 2 zset1 zset2 WEIGHTS 2 1 |
Union of sorted sets |
ZINTERSTORE |
ZINTERSTORE out 2 zset1 zset2 |
Intersection |
ZPOPMIN |
ZPOPMIN leaderboard 1 |
Pop lowest score |
ZPOPMAX |
ZPOPMAX leaderboard 1 |
Pop highest score |
BZPOPMIN |
BZPOPMIN leaderboard 10 |
Blocking pop min |
BZPOPMAX |
BZPOPMAX leaderboard 10 |
Blocking pop max |
Use cases: Leaderboards, rate limiting, priority queues, time-series data with scores as timestamps
| Command | Example | Description |
|---|---|---|
SETBIT |
SETBIT online:2025-01-15 1001 1 |
Set bit at offset |
GETBIT |
GETBIT online:2025-01-15 1001 |
Get bit |
BITCOUNT |
BITCOUNT online:2025-01-15 |
Count 1 bits |
BITOP |
BITOP OR dest src1 src2 |
AND, OR, XOR, NOT |
BITPOS |
BITPOS key 1 |
Find first 1 bit |
BITFIELD |
BITFIELD key GET u8 0 |
Advanced bit operations |
Use cases: User activity tracking, real-time analytics, feature flags
| Command | Example | Description |
|---|---|---|
PFADD |
PFADD unique_visitors "ip1" "ip2" |
Add elements |
PFCOUNT |
PFCOUNT unique_visitors |
Approx count (error ~0.81%) |
PFMERGE |
PFMERGE dest src1 src2 |
Merge multiple HLLs |
Use cases: Unique visitor counting, search term distinct counts
Based on Sorted Sets, stores longitude, latitude with member
| Command | Example | Description |
|---|---|---|
GEOADD |
GEOADD cities 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania" |
Add locations |
GEOPOS |
GEOPOS cities Palermo |
Get coordinates |
GEODIST |
GEODIST cities Palermo Catania km |
Distance (m, km, mi, ft) |
GEORADIUS |
GEORADIUS cities 15 37 100 km WITHDIST COUNT 5 |
Query by center |
GEORADIUSBYMEMBER |
GEORADIUSBYMEMBER cities Palermo 100 km |
Query around member |
GEOSEARCH |
GEOSEARCH cities FROMLONLAT 15 37 BYRADIUS 100 km |
Newer version (Redis 6.2+) |
GEOSEARCHSTORE |
GEOSEARCHSTORE dest cities ... |
Store result |
Use cases: Nearby restaurants, delivery zone check, location-based services
Append-only log (like Kafka). Redis 5.0+
| Command | Example | Description |
|---|---|---|
XADD |
XADD mystream * sensor-id 1234 temperature 22.5 |
Add entry (* = auto ID) |
XREAD |
XREAD COUNT 2 STREAMS mystream 0 |
Read entries |
XREAD (blocking) |
XREAD BLOCK 5000 STREAMS mystream $ |
Block until new entry |
XRANGE |
XRANGE mystream - + |
Range by IDs |
XREVRANGE |
XREVRANGE mystream + - |
Reverse range |
XLEN |
XLEN mystream |
Length |
XDEL |
XDEL mystream 123456789-0 |
Delete entry |
XTRIM |
XTRIM mystream MAXLEN ~ 1000 |
Trim stream |
XGROUP CREATE |
XGROUP CREATE mystream mygroup 0 |
Create consumer group |
XREADGROUP |
XREADGROUP GROUP mygroup consumer1 COUNT 10 STREAMS mystream > |
Read from group |
XACK |
XACK mystream mygroup 123456789-0 |
Acknowledge |
XPENDING |
XPENDING mystream mygroup |
Pending entries |
XCLAIM |
XCLAIM mystream mygroup consumer1 3600000 id1 |
Claim stale entries |
XINFO |
XINFO STREAM mystream |
Stream info |
Use cases: Event sourcing, message queues (with consumer groups), real-time data pipelines
| Command | Example | Description |
|---|---|---|
DEL |
DEL key1 key2 |
Delete keys |
UNLINK |
UNLINK key |
Non-blocking delete |
EXISTS |
EXISTS key |
Check existence |
TYPE |
TYPE key |
Data type |
RENAME |
RENAME old new |
Rename key |
RENAMENX |
RENAMENX old new |
Rename if new not exists |
KEYS |
KEYS user:* |
|
SCAN |
SCAN 0 MATCH user:* COUNT 100 |
Cursor-based iteration |
RANDOMKEY |
RANDOMKEY |
Get random key |
SORT |
SORT list ALPHA LIMIT 0 5 |
Sort list/set |
COPY |
COPY src dst |
Copy key |
OBJECT |
OBJECT ENCODING key |
Internal encoding |
| Command | Example | Description |
|---|---|---|
EXPIRE |
EXPIRE key 60 |
Set expiry (seconds) |
PEXPIRE |
PEXPIRE key 60000 |
Set expiry (milliseconds) |
EXPIREAT |
EXPIREAT key 1735689600 |
Expire at Unix timestamp |
TTL |
TTL key |
Remaining TTL (sec, -1 = no expiry, -2 = missing) |
PTTL |
PTTL key |
Remaining TTL (ms) |
PERSIST |
PERSIST key |
Remove expiry |
Atomic, isolated, not rollback-capable
MULTI # Start transaction
SET account:1 100
SET account:2 200
INCRBY account:1 50
DECRBY account:2 50
EXEC # Execute (or DISCARD to cancel)
WATCH account:1 # Monitor key for changes
val = GET account:1
MULTI
SET account:1 val+1
EXEC # Fails if account:1 changed
| Command | Description |
|---|---|
MULTI |
Start transaction |
EXEC |
Execute all commands |
DISCARD |
Abort transaction |
WATCH |
Monitor keys for changes |
UNWATCH |
Unwatch all keys |
Atomic execution of complex logic. EVAL and SCRIPT commands
EVAL "return redis.call('SET', KEYS[1], ARGV[1])" 1 mykey "hello"
-- KEYS[1], KEYS[2], ... for key names
-- ARGV[1], ARGV[2], ... for arguments
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local current = tonumber(redis.call('GET', key) or 0)
if current < limit then
redis.call('INCR', key)
return 1
else
return 0
end| Command | Example | Description |
|---|---|---|
EVAL |
EVAL "script" 1 key arg |
Execute script |
EVALSHA |
EVALSHA sha1 1 key arg |
Execute cached script |
SCRIPT LOAD |
SCRIPT LOAD "script" |
Cache script → returns SHA |
SCRIPT EXISTS |
SCRIPT EXISTS sha1 |
Check if cached |
SCRIPT FLUSH |
SCRIPT FLUSH |
Clear script cache |
SCRIPT KILL |
SCRIPT KILL |
Kill running script (if no writes) |
- Use EVALSHA after SCRIPT LOAD (reduces bandwidth)
- Keep scripts short (avoid loops over large datasets)
- Scripts block Redis (no other commands run)
- Use
redis.replicate_commands()for non-deterministic writes (Redis 3.2+)
Fire-and-forget pattern. Messages not persisted.
| Command | Example | Description |
|---|---|---|
SUBSCRIBE |
SUBSCRIBE channel1 channel2 |
Subscribe to channels |
PSUBSCRIBE |
PSUBSCRIBE news.* |
Pattern subscribe |
PUBLISH |
PUBLISH channel1 "hello" |
Send message |
UNSUBSCRIBE |
UNSUBSCRIBE channel1 |
Unsubscribe |
PUNSUBSCRIBE |
PUNSUBSCRIBE news.* |
Pattern unsub |
PUBSUB CHANNELS |
PUBSUB CHANNELS news.* |
List active channels |
PUBSUB NUMSUB |
PUBSUB NUMSUB channel1 |
Subscriber count |
SUBSCRIBE notifications
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "notifications"
3) (integer) 1
PUBLISH notifications "Hello world"
(integer) 1
Use cases: Real-time notifications, chat systems, live feeds
Extend Redis functionality. Enterprise & OSS modules
| Module | Description | Commands |
|---|---|---|
| RediSearch | Full-text search, secondary indexing | FT.CREATE, FT.SEARCH, FT.AGGREGATE |
| RedisJSON | JSON document storage | JSON.SET, JSON.GET, JSON.ARRAPPEND |
| RedisTimeSeries | Time-series data | TS.CREATE, TS.ADD, TS.RANGE |
| RedisBloom | Probabilistic data structures | BF.ADD, CF.ADD, CMS.INCRBY, TOPK.ADD |
| RedisGraph | Graph database (deprecated) | GRAPH.QUERY |
| RedisAI | ML model serving | AI.MODELSET, AI.TENSORSET |
JSON.SET user:1 $ '{"name": "Alice", "age": 30}'
JSON.GET user:1 $.name
JSON.ARRAPPEND user:1 $.tags '"redis"'
redis-server --loadmodule /path/to/module.soPros: Compact, faster restarts
Cons: Potential data loss between snapshots
Configure in redis.conf:
save 900 1 # Save if at least 1 key changed in 900 sec
save 300 10 # Save if 10 keys changed in 300 sec
save 60 10000 # Save if 10000 keys changed in 60 sec
dbfilename dump.rdb
dir /var/lib/redis
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
Commands:
SAVE # Blocking save
BGSAVE # Background save (fork)
LASTSAVE # Last save timestamp
Pros: More durable (loss: 1 sec max)
Cons: Larger files, slower restores
Configuration:
appendonly yes
appendfilename "appendonly.aof"
appendfsync always # Every write (slowest, safest)
appendfsync everysec # Every second (recommended)
appendfsync no # OS decides (fastest, least safe)
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
Commands:
BGREWRITEAOF # Rewrite AOF (compact)
aof-use-rdb-preamble yes # RDB header + incremental AOF
Master redis.conf:
replica-read-only yes
Slave redis.conf:
replicaof 192.168.1.100 6379
masterauth yourpassword
replica-read-only yes
Commands:
INFO replication # Show replication status
REPLICAOF 192.168.1.100 6379 # Set up replication
REPLICAOF NO ONE # Promote to master
WAIT 1 5000 # Wait for replication (replicas, timeout ms)
Sentinel config sentinel.conf:
sentinel monitor mymaster 127.0.0.1 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel parallel-syncs mymaster 1
sentinel auth-pass mymaster yourpassword
Commands:
SENTINEL masters
SENTINEL slaves mymaster
SENTINEL get-master-addr-by-name mymaster
SENTINEL failover mymaster
SENTINEL reset mymaster
Run Sentinel:
redis-sentinel /path/to/sentinel.confHorizontal scaling with sharding. 16384 hash slots.
- Minimum 3 masters, 3 slaves for production
Create Cluster:
redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 \
127.0.0.1:7002 127.0.0.1:7003 \
127.0.0.1:7004 127.0.0.1:7005 \
--cluster-replicas 1Cluster Commands:
CLUSTER INFO # Cluster state
CLUSTER NODES # Node information
CLUSTER SLOTS # Slot mapping
CLUSTER MEET host port # Add node
CLUSTER FORGET node-id # Remove node
CLUSTER ADDSLOTS slot # Assign slots to master
CLUSTER KEYSLOT key # Hash slot for key
CLUSTER COUNTKEYSINSLOT slot # Keys in slot
Resharding:
redis-cli --cluster reshard 127.0.0.1:7000 --cluster-from node-id --cluster-to node-id --cluster-slots 1000Important: Multi-key operations only work if keys are in same slot (use Hash Tags):
SET {user:123}.name "Alice"
SET {user:123}.age "30"
| Setting | Recommended | Description |
|---|---|---|
maxmemory |
4gb (example) |
Maximum memory usage |
maxmemory-policy |
allkeys-lru |
Eviction policy |
maxmemory-samples |
5 |
LRU sampling size |
Eviction Policies:
noeviction- Return error on maxmemoryallkeys-lru- Evict least recently usedallkeys-lfu- Least frequently usedvolatile-lru- Among keys with expiryallkeys-random- Random evictionvolatile-ttl- Evict shortest TTL first
Use smaller data types:
# Instead of many small keys
HSET user:1 name "Alice" age 30
# Use integers when possible
SET counter:1 123
# Use ziplist (small hashes/lists)
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
| Setting | Value | Effect |
|---|---|---|
tcp-backlog |
511 |
Connection backlog |
timeout |
0 |
Close idle clients |
tcp-keepalive |
300 |
TCP keepalive |
io-threads |
4 |
I/O threads (non-CPU bound) |
io-threads-do-reads |
yes |
Enable read threads |
auto-aof-rewrite-percentage |
100 |
AOF rewrite trigger |
CONFIG SET slowlog-log-slower-than 10000 # microseconds
CONFIG SET slowlog-max-len 128
SLOWLOG GET 10
SLOWLOG LEN
SLOWLOG RESET
- Keep connections open, reuse them
- Typical pool size: 10-50 per instance
# Python example
pipe = redis.pipeline()
pipe.incr('counter1')
pipe.incr('counter2')
pipe.incr('counter3')
results = pipe.execute()In redis.conf:
requirepass yourstrongpassword
masterauth yourstrongpassword # For replicas
Command-line:
AUTH yourstrongpassword
ACL (Redis 6.0+):
# Create user
ACL SETUSER alice ON >password ~* +@all
# Restrict commands
ACL SETUSER monitor OFF >temp123 +INFO +PING
# Restrict keys
ACL SETUSER app1 ON >pass ~cached:* +get +set
# List users
ACL LIST
ACL USERS
# Who am I
ACL WHOAMI
ACL File (redis.conf):
user alice on #password ~* +@all
user bob off +@dangerous
Redis config:
tls-port 6380
port 0
tls-cert-file /path/to/redis.crt
tls-key-file /path/to/redis.key
tls-ca-cert-file /path/to/ca.crt
tls-auth-clients yes
bind 127.0.0.1 192.168.1.100 # Listen on specific IPs
protected-mode yes # Protect if no bind & no password
rename-command FLUSHALL ""
rename-command CONFIG "RENAME_CONFIG"
rename-command SHUTDOWN "SHUTDOWN_SAFE"
INFO # All stats
INFO stats # Command stats, rejections
INFO memory # Memory usage
INFO clients # Client connections
INFO persistence # RDB/AOF status
INFO replication # Master/slave status
INFO keyspace # Keys per DB
INFO commandstats # Command latency/calls
CLIENT LIST # Connected clients
CLIENT KILL addr:port # Kill client
MEMORY STATS # Memory breakdown
MEMORY USAGE key # Memory used by key
MEMORY DOCTOR # Memory diagnostics
LATENCY LATEST # Latency spikes
LATENCY HISTORY command
LATENCY RESET
COMMAND STATS # Command statistics
COMMAND INFO ... # Command details
CONFIG RESETSTAT # Reset all stats
INFO commandstats # View command stats
MONITOR
- Redis Insight (GUI)
- Prometheus + Redis Exporter
- Datadog, New Relic, Dynatrace
redis-cli --stat(real-time)redis-cli --latency -h host -p 6379redis-cli --bigkeys(scan large keys)redis-cli --hotkeys(with LFU policy)
DEBUG OBJECT key
DEBUG SEGFAULT # (Intentional crash)
PING # Check if alive
redis.conf:
loglevel notice # debug, verbose, notice, warning
logfile /var/log/redis/redis-server.log
syslog-enabled yes
syslog-ident redis
| Language | Library | Connection String |
|---|---|---|
| Python | redis-py | redis.Redis(host='localhost', port=6379, db=0) |
| Node.js | ioredis | new Redis({host:'localhost', port:6379}) |
| Java | Jedis / Lettuce | new Jedis('localhost', 6379) |
| Go | go-redis | redis.NewClient(&redis.Options{Addr:"localhost:6379"}) |
| Ruby | redis-rb | Redis.new(host:"localhost", port:6379) |
| PHP | Predis / phpredis | new Predis\Client('tcp://localhost:6379') |
| C# | StackExchange.Redis | ConnectionMultiplexer.Connect("localhost:6379") |
| Rust | redis-rs | redis::Client::open("redis://localhost/") |
import redis
r = redis.Redis(
host='localhost',
port=6379,
password='yourpass',
decode_responses=True,
socket_keepalive=True,
retry_on_timeout=True
)
# Basic operations
r.set('key', 'value')
print(r.get('key'))
# Pipeline
pipe = r.pipeline()
pipe.incr('counter')
pipe.expire('counter', 60)
pipe.execute()
# Pub/Sub
pubsub = r.pubsub()
pubsub.subscribe('channel')
for message in pubsub.listen():
print(message)| Task | Command |
|---|---|
| Connect | redis-cli -a password |
| Check health | PING |
| Get all keys | KEYS * (dev only) or SCAN 0 |
| Flush all | FLUSHALL / FLUSHDB |
| Backup | BGSAVE / LASTSAVE |
| Config | CONFIG GET * / CONFIG SET param value |
| Stats | INFO stats / INFO memory |
| Slow queries | SLOWLOG GET 10 |
| Big keys | redis-cli --bigkeys |
| Monitor | MONITOR (careful) |
| Shutdown | SHUTDOWN SAVE / SHUTDOWN NOSAVE |
| Pattern | Example |
|---|---|
| Cache | cache:user:123 → TTL 3600 |
| Session | session:abc123 → TTL 7200 |
| Counter | stats:pageviews:homepage |
| Queue | queue:tasks (list) |
| Lock | lock:resource:123 → SETNX + TTL |