Redis
Keys & Expiration
Set TTL, scan keys, and inspect the keyspace.
By EZ4Code Team
ttlexpirationscan
Code
# Set TTL on existing keys
EXPIRE session:abc 3600 # seconds
EXPIREAT cache:hot 1700000000 # unix timestamp
PEXPIRE token:xyz 60000 # milliseconds
TTL session:abc
PTTL session:abc
# Set + TTL atomically
SET token:xyz "data" EX 60
# Persist (remove TTL)
PERSIST session:abc
# Inspect the keyspace
KEYS user:* # avoid in production
SCAN 0 MATCH user:* COUNT 100
TYPE user:1
OBJECT IDLETIME user:1
RANDOMKEY
DBSIZEExplanation
EXPIRE sets a TTL on a key after which Redis removes it automatically; SET with EX is the atomic way to set value and TTL together. KEYS blocks the server on large keyspaces, so prefer SCAN for production iteration. OBJECT IDLETIME helps find rarely-accessed cache entries to evict.
More Redis Snippets
Strings & Counters
Set, get, increment, and expire string values.
Lists & Queues
Build queues and stacks with list operations.
Hashes
Store object fields and values efficiently.
Sets
Manage unique collections and compute intersections.
Sorted Sets & Leaderboards
Rank items by score for leaderboards and scheduling.
Pub/Sub
Broadcast messages to subscribed clients.