Redis Basics
Redis is an in-memory key-value store.
Redis use case
- Cache data
- User session
Installation
Download, extract and compile Redis
1 | $ wget http://download.redis.io/releases/redis-5.0.3.tar.gz |
The binaries are located at the src directory. To start the server:
1 | ./src/redis-server & |
default port is 6379
To start a Redis CLI
1 | ./src/redis-cli |
To test Redis using CLI
1 | 127.0.0.1:6379> set foo bar |
There is also a Docker Image for Redis you can use.
1 | docker run -d --rm -p 6379:6379 --name redis-demo redis |
You can then get into the container using bash or sh command.
1 | docker exec -it redis-demo bash |
Redis container has installed redis-cli
you can use to interact with redis.
1 | # redis-cli |
Redis Keys
You can use any binary sequence as a key, meaning you can use string or even JPEG file. Maximum key size is 512M.
Try to stick with a schema for the key. convention is to use colon(:). For Instance “user:100”, “user:100:password”. for multi-words key, use dots. comment:1234:replay.to”
KEYS
KEYS command Returns all keys matching pattern.
show keys matching pattern
1 | > KEYS *name* |
show all keys
1 | > KEYS * |
DEL
Use DEL Command to delete a key
1 | > DEL mykey |
TYPE
Use TYPE Command to check the type of a key
1 | > TYPE firstname |
The return type can be “string”, “hash”, “list”, “set” or “zset”.
Data Types
String
The simpliest data structure
1 | > SET site:about "this is my site" |
Hash
data type to store objects.
1 | > HSET books:helloredis title "hello redis" |
HGETALL Command Returns all fields and values of the hash stored at key. In the return value, every field name is followed by its value, so the length of the reply is twice the size of the hash.
1 | > HGETALL books:helloredis |
List
An array of values.
1 | > LPUSH books:helloredis:authors 'alice' 'bob' |
Set
unordered collection of values
1 | > SADD books:helloredis:tags nosql in-memory |
You can use SETEX
command to set timeout in seconds
1 | > SETEX mykey 10 "Hello" |
Sorted Set
values are associated with a score. score is used for sorting.
1 | > ZADD tags 1 redis |
Pub/Sub
Redis supports Pub/Sub. senders(publishers) can send messages to specific receivers(subscribers).
To subscribe to a channel
1 | > subscribe foo |
To publish a message to foo
1 | > publish foo "Hello Redis" |
Other Commands
Monitor
MONITOR is a debugging command that streams back every command processed by the Redis server. It can help in understanding what is happening to the database.
1 | > monitor |