Redis

Before Redis, Memcached was a common key-value store. PHP, with its short-lived processes, necessitated a standalone cache service like Memcached because in-memory caching was ineffective.

Long-lived processes (e.g., Node.js) can often rely on in-memory caching. However, scenarios requiring shared state across multiple application instances still benefit from a standalone solution.

Redis extends beyond basic key-value caching by offering diverse data structures like lists, sets, and HyperLogLog etc. This versatility enables its use in various applications such as session storage, task queues, rate limiting, leaderboards, and more.

Setup

docker run -d --name my-redis-stack -p 6379:6379 redis/redis-stack-server:latest

Talk to the server:

docker exec -it my-redis-stack redis-cli
127.0.0.1:6379> PING
PONG

Basic Data Structures and Operations

A comprehensive list of Redis Commands can be found here.

Strings

127.0.0.1:6379> SET key value
OK
127.0.0.1:6379> GET key
"value"

Hashes

127.0.0.1:6379> HMSET user:1 name John age 30
OK
127.0.0.1:6379> HGET user:1 age
"30"

: in user:1 is used as a separator in the key

Lists

127.0.0.1:6379> LPUSH mylist item1 item2
(integer) 2
127.0.0.1:6379> LRANGE mylist 0 -1
1) "item2"
2) "item1"

Sets

127.0.0.1:6379> SADD myset element1 element2
(integer) 2
127.0.0.1:6379> SMEMBERS myset
1) "element1"
2) "element2"

Zsets

Zsets are ordered sets where each element has a score.

127.0.0.1:6379> ZADD myzset 1 item1 2 item2
(integer) 2
127.0.0.1:6379> ZRANGE myzset 0 -1 WITHSCORES
1) "item1"
2) "1"
3) "item2"
4) "2"

Use Redis in Node.js

There is the official client node-redis, but ioredis offers better develper experience.