Redis CLI Basics¶
See Overview for install. All of this is redis-cli, either interactively or as one-off invocations.
Connecting and a Sanity Check¶
redis-cli
127.0.0.1:6379> ping
PONG
Strings and Counters¶
127.0.0.1:6379> SET foo 100
OK
127.0.0.1:6379> GET foo
"100"
127.0.0.1:6379> INCR foo
(integer) 101
127.0.0.1:6379> INCR foo
(integer) 102
127.0.0.1:6379> DECR foo
(integer) 101
INCR/DECR are atomic — safe to use as a shared counter across concurrent clients without a separate lock, which is a big part of why Redis is a common choice for rate limiters and counters specifically.
Existence and Deletion¶
127.0.0.1:6379> SET bar 200
OK
127.0.0.1:6379> EXISTS bar
(integer) 1
127.0.0.1:6379> EXISTS bar2
(integer) 0
127.0.0.1:6379> DEL bar
(integer) 1
127.0.0.1:6379> EXISTS bar
(integer) 0
One-Off Commands From the Shell¶
redis-cli ECHO Hello
redis-cli GET foo
redis-cli INCR foo
Useful in scripts — pipe or redirect output the normal way:
redis-cli INCR foo > commands.txt
Watching Live Traffic¶
MONITOR streams every command the server receives in real time — invaluable for seeing exactly what an application is actually sending, but expensive under real load (it has a measurable performance cost since every command now also has to be echoed to the monitoring connection). Use briefly for debugging, not as a standing dashboard.
127.0.0.1:6379> monitor
OK
In another shell:
127.0.0.1:6379> INCR foo
(integer) 104
Back in the monitoring session:
1486676100.716469 [0 127.0.0.1:40462] "INCR" "foo"
Clearing Everything¶
127.0.0.1:6379> FLUSHALL
OK
127.0.0.1:6379> GET foo
(nil)
FLUSHALL clears every database on the instance immediately and irreversibly — there's no confirmation prompt. Double-check you're connected to the instance you think you are before running it, especially if you keep a shell history that makes it easy to re-run against the wrong host.
Namespacing Keys¶
Redis has no built-in concept of tables/collections — convention (usually a :-delimited prefix) is what keeps keys organized:
127.0.0.1:6379> SET server:name redis1.example.local
OK
127.0.0.1:6379> GET server:name
"redis1.example.local"
127.0.0.1:6379> SET server:port 6380
OK
Expiry (TTL)¶
127.0.0.1:6379> SET resource:foo hello
OK
127.0.0.1:6379> EXPIRE resource:foo 120
(integer) 1
127.0.0.1:6379> TTL resource:foo
(integer) 61
127.0.0.1:6379> TTL resource:foo
(integer) 21
127.0.0.1:6379> TTL resource:foo
(integer) -2
TTL return values worth remembering:
- A positive number — seconds remaining
- -1 — the key exists but has no expiry set
- -2 — the key doesn't exist (either it never did, or its TTL already elapsed)
Re-SET-ting a key clears any previously set expiry unless you use SET ... KEEPTTL (or re-apply EXPIRE after):
127.0.0.1:6379> SET resource:foo hello
OK
127.0.0.1:6379> TTL resource:foo
(integer) -1
Related¶
- Cluster — scaling beyond a single instance