Redis Cli Commands Cheat Sheet



Redis CLI Cheat Sheet

##Start Redis Server

The basic syntax of Redis client. $redis-cli Run Commands on the Remote Server. You need to connect to the server by the same client redis-cli $ redis-cli -h host -p. The MEMORY STATS command returns an Array reply about the memory usage of the server. The information about memory usage is provided as metrics and their respective values. The following metrics are reported: peak.allocated: Peak memory consumed by Redis in bytes (see INFO's usedmemorypeak); total.allocated: Total number of bytes allocated by Redis using its allocator (see.

The MEMORY STATS command returns an Array reply about the memory usage of the server. The information about memory usage is provided as metrics and their respective values. The following metrics are reported: peak.allocated: Peak memory consumed by Redis in bytes (see INFO's usedmemorypeak). Common Linux Commands; Compiling Notes; Create a Private Signed Cert Example; Debian Notes. Redis Cheat Sheet¶ Connect to redis: $ redis-cli Select a DB: redis 127.0.0.1:6379 SELECT 4 List all keys: redis 127.0.0.1:6379 KEYS. Delete a key: redis 127.0.0.1:6379 DEL mykeyname.

>redis-server

##Start Redis Client

>redis-cli
127.0.0.1:6379>

##Push list of items to a specific key, retrieve them by range

127.0.0.1:6379> lpush testpush 5 2 3 4
(integer) 4
127.0.0.1:6379> lpush testpush “hello world”
(integer) 5
127.0.0.1:6379> lrange testpush 0 -1
1) “hello world”
2) “4”
3) “3”
4) “2”
5) “5”

127.0.0.1:6379> lrange testpush 0 2

1) “hello world”
2) “4”
3) “3”

##Trim list to contain only specified range of items

127.0.0.1:6379> ltrim testpush 1 4
OK
127.0.0.1:6379> lrange testpush 0 -1
1) “4”
2) “3”
3) “2”
4) “5”

127.0.0.1:6379> lrange testpush 0 -1
1) “5”
2) “5”
3) “add one more”
4) “4”
5) “3”
6) “2”

127.0.0.1:6379> lrem testpush -2 “5”
(integer) 2
127.0.0.1:6379> lrange testpush 0 -1
1) “add one more”
2) “4”
3) “3”
4) “2”

##ZSET store a mapping of members to scores

127.0.0.1:6379> ZADD testzet 1 “one” 2 “two” 3 “three”
(integer) 3
127.0.0.1:6379> ZRANGE testzet 0 10
1) “one”
2) “two”
3) “three”
127.0.0.1:6379> ZRANGE testzet 0 1
1) “one”
2) “two”
127.0.0.1:6379> ZRANK testzet “one”
(integer) 0
127.0.0.1:6379> ZSCORE testzet “one”
“1”
127.0.0.1:6379> ZCOUNT testzet 1 2
(integer) 2
127.0.0.1:6379> ZCARD testzet
(integer) 3

#Set expiration time on key

127.0.0.1:6379> expire testzet 10
(integer) 1
127.0.0.1:6379> ttl testzet
(integer) 0
127.0.0.1:6379> keys *
1) “testpush”

##Counter Operations

127.0.0.1:6379> SET test:1:hit:total 2014
OK
127.0.0.1:6379> SET test:2:hit:total 2014
OK
127.0.0.1:6379> INCR test:1:hit:total
(integer) 2015
127.0.0.1:6379> GET test:1:hit:total
“2015”

127.0.0.1:6379> HSET testhash field1 “yellow”
(integer) 1
127.0.0.1:6379> HSET testhash field2 “blue”
(integer) 1
127.0.0.1:6379> HSET users:test name “yellow apple”
(integer) 1
127.0.0.1:6379> HSET users:test email “yellow.apple@gmail.com”
(integer) 1
127.0.0.1:6379> HSET users:test phone “12345”
(integer) 1
127.0.0.1:6379> HSET users:test visit 100
(integer) 1
127.0.0.1:6379> HINCRBY users:test visit 20
(integer) 120
127.0.0.1:6379> HGET users:testi visit
“120”
127.0.0.1:6379> HGETALL users:test
1) “name”
2) “yellow apple”
3) “email”
4) “yellow.apple@gmail.com”
5) “phone”
6) “12345”
7) “visit”
8) “120”
127.0.0.1:6379> HKEYS users:test
1) “name”
2) “email”
3) “phone”
4) “visit”
127.0.0.1:6379> HVALS users:test
1) “yellow apple”
2) “yellow.apple@gmail.com”
3) “12345”
4) “120”

## Set operations and member control

127.0.0.1:6379> SADD testhset “one”
(integer) 1
127.0.0.1:6379> SADD testhset “two”
(integer) 1
127.0.0.1:6379> SCARD testhset
(integer) 2
127.0.0.1:6379> SPOP testhset
“one”
127.0.0.1:6379> SCARD testhset
(integer) 1

##Publish/Subscribe on channel

127.0.0.1:6379> SUBSCRIBE redisChat
Reading messages… (press Ctrl-C to quit)
1) “subscribe”
2) “redisChat”
3) (integer) 1

1) “message”
2) “redisChat”
3) “Redis is a great caching technique”
1) “message”
2) “redisChat”
3) “hello from publisher”

127.0.0.1:6379> PUBLISH redisChat “Redis is a great caching technique”
(integer) 1
127.0.0.1:6379> PUBLISH redisChat “hello from publisher”
(integer) 1
127.0.0.1:6379> PUBLISH redisChat “hello from publisher”
(integer) 0
127.0.0.1:6379> PUBLISH redisChat “hello from publisher”
(integer) 1

##Redis as message queue

127.0.0.1:6379> RPUSH testQueue a b c
(integer) 3

127.0.0.1:6379> BLPOP testQueue 0
1) “testQueue”
2) “a”
(17.07s)
127.0.0.1:6379>

Web Use Cases

Cache latest items in the user’s home page

Expect: – have live and fast update cache view with limited items, page with uniquely defined key

Redis Cli Commands Cheat Sheet

LPUSH : define unique user page key, insert items to the keyed list with LIFO order

LRANGE: retrieve items by order range

LTRIM: limit items in the cache for the page

LREM: remove items by value and occurrence in the list of page key

Cache items for leaderboards, which items are in sorted set by score

ZADD: add items with their score to the unique key set and sorted with O(log(N)) and updating score causes overwrite and re-sort

ZREVRANGE: get top N items from the set

ZRANK: get item’s rank

Cache items to reorder from user vote, which items are re-ranked with updated score

LPUSH: add items to cache

backend task polls the item list and recompute order, use zadd to set rank

ZADD: update items with score

ZREVRANGE: get top N items from the set

Cache items to be expired by time

Option 1: Sorted Set

-Sorted Set cannot set a TTL to individual items, cannot automatically

-Use ZADD UNIX timestamp to identify expiration time as score, and sorted in the set,

– item as activity + “-” + System.currentTime()

– ttl as System.currentTime() + expiration-period-in-long, UTC

– ZADD myzet ttl item

-Use ZREMRANGEBYSCORE to remove the expired items

– ZREMRANGEBYSCORE mizen -inf (System.currentTime())

-Run a backend job to remove expired items with above command

-Pros: simple and straightforward, single data set to visit, extra info to associate date with data

-Cons: extra cleanup job to maintain

Option 2: Set TTL to whole set by its key

Redis can automatically remove the key based on the expire TTL time

–LPUSH mylist item

-ttl as System.currentTime() + expiration-period-in-long, UTC

–EXPIRE mylist ttl

–TTL mylist

-Pros: no extra clean up job

-Cons: not guarantee cleanup

Redis Cli Command Line

Cache items as counter, metrics, like usage, hits, which Redis has atomicity data type

Single Counter

-Design namespace for the counter as key, build key with “:” as separator

-Maintain counter through INCR, DECR, SET, GET and also have float as BYFLOAT, BITOP etc.

-Reset counter with GETSET to reset automatically

-Expire counter with EXPIRE

Counter in Hash

-Design namespace for hash as key, build key with “:” as separator

–HSET and HINCRBY

-??Reset counter inside hash

-??Expire counter inside hash

Cache N items in given timer period, like unique visitors

–SADD to add items to set as unique

–SCARD to get size of the set and used it to limit N

–EXPIRE whole set

-Or use ZADD with ttl as score and clean job

Real time analysis of what is happening, for stats, anti-spam, filter

Pub/Sub used as buffer/channel/circle, keeping a map of subscribers and publish them for updates

PUBLISH allows you to push a message into a channel

SUBSCRIBE will listen to a channel

Messages sent by other clients to these channels will be pushed by Redis to all the subscribed clients.

A client subscribed to one or more channels should not issue commands, although it can subscribe and unsubscribe to and from other channels. The replies to subscription and unsubscription operations are sent in the form of messages, so that the client can just read a coherent stream of messages where the first element indicates the type of message.

Format of pushed messages

A message is a Array reply with three elements.

The first element is the kind of message:

  • subscribe: means that we successfully subscribed to the channel given as the second element in the reply. The third argument represents the number of channels we are currently subscribed to.
  • unsubscribe: means that we successfully unsubscribed from the channel given as second element in the reply. The third argument represents the number of channels we are currently subscribed to. When the last argument is zero, we are no longer subscribed to any channel, and the client can issue any kind of Redis command as we are outside the Pub/Sub state.
  • message: it is a message received as result of a PUBLISH command issued by another client. The second element is the name of the originating channel, and the third argument is the actual message payload.

The second element is the kind of message: channel name

The third element is the message content: string

Pattern on channel and message

Redis Cli Commands

A client may receive a single message multiple times if it’s subscribed to multiple patterns matching a published message, or if it is subscribed to both patterns and channels matching the message.

Redis RESP protocol

In RESP, the type of some data depends on the first byte:

  • For Simple Strings the first byte of the reply is “+”
  • For Errors the first byte of the reply is “-“
  • For Integers the first byte of the reply is “:”
  • For Bulk Strings the first byte of the reply is “$”
  • For Arrays the first byte of the reply is “*

Redis as message queue with LIST structure

RPUSH: as producer to push message into tail of the list, multiple items pushed in the order of leftmost to rightmost

BLPOP: as consumer to get the first message from the list and block if queue is empty

The blocking queue behavior can be used as lock for different primitives, like

Consumer:

LOOP forever

While S (key) returns elements

… process elements

END

BRPOP helper_key

END

Producer: uses transaction

MULTI #location txn

SADD key element

LPUSH helper_key x

EXEC

Redis execute multiple commands in transaction

MULTI: marker to start a transaction to execute the subsequent command in a queued for atomic

EXEC: executes all previously queued commands in a transaction and restores the connection state to normal.

DISCARD: exit transaction with flushing the queued commands

Error aborts transaction and roll back command since Redis 2.6.5

Transaction lock: WATCH is used to provide a check-and-set (CAS) behavior to Redis transactions.