Redis (Remote Dictionary Server) is a BSD licensed, in-memory data structure store, used as a distributed, in-memory key–value database, cache and message broker.
It can store different kinds of abstract data structures, such as
- Strings
- Lists
- Hash maps
- Sets
- Sorted sets
When use Redis/Example use case
Redis, is NOT a NoSQL replacement for classic relational databases, as it doesn’t support many features of RDBMS, such as querying of your data which might slow it down.
Replacements for RDBMS are rather document databases like MongoDB or CouchDB.
Redis is great at specific functionality where speed and support for advanced data structures is crucial.
Running the server
I have installed the redis via docker so:
1 2 |
docker pull redis docker run -it --name my-redis redis |
Now open another terminal, get into the docker container and connect to the server:
1 2 |
docker exec -it my-redis bash redis-cli |
You can log into redis server via:
redis-cli -h <host-address> -p <port> -a <password>
or
redis-cli -u redis://username:password@host:port
Redis CONFIG
The configuration file “redis.conf” in redis, is located at the root directory of Redis. You can get/set all Redis configurations by Redis CONFIG command.
Get all configuration:
1 |
CONFIG GET * |
This will set password temporarily (until redis or server restart)
1 |
CONFIG SET requirepass mypass |
To get the location of the data directory in Redis
1 |
redis-cli config get dir |
Keys
Set key to hold the string value. If key already holds a value, it is overwritten,
1 2 3 |
SET greetings 'hello' SETEX greetings 1000 'hello' SET greetings 'hello' EX 1000 |
Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at the key is not a string, because GET only handles string values.
1 |
GET greetings |
This command checks whether the key exists or not.
1 |
EXISTS greetings |
Sets the expiry of the key after the specified time.
1 |
EXPIRE greeting 1000 |
Gets the remaining time in keys expiry.
1 |
TTL greeting |
Removes the expiration from the key.
1 |
PERSIST greeting |
Get all the keys matching pattern.
1 2 |
KEYS * KEYS ?? |
Returns the data type of the value stored in the key.
1 |
TYPE greetings |
Refs: [1]
Lists
Prepends one or multiple values to a list
1 2 3 4 |
LPUSH mylist 'list' LPUSH mylist 'new' LPUSH mylist 'is' LPUSH mylist 'this' |
Gets a range of elements from a list
1 |
LRANGE mylist 0 -1 |
Refs: [1]
Hash maps
Hash maps are the perfect data type to represent objects.
Sets the string value of a hash field
1 2 3 |
HSET student name behnam HSET student age 37 HSET student gender M |
Sets multiple hash fields to multiple values
1 |
HMSET student name ben age 40 gender M |
Gets the value of a hash field stored at the specified key.
1 |
HGET student name |
Gets all the fields and values stored in a hash at the specified key
1 |
HGETALL student |
Gets all the fields in a hash
1 |
HKEYS student |
Sets /Sorted sets
Publish/ Subscribe
Listens for messages published to the given channels.
1 |
SUBSCRIBE chat |
Posts a message to a channel.
1 |
PUBLISH chat 'hey there' |
see what channels are currently available:
1 |
PUBSUB CHANNELS * |
Returns the number of subscribers of the channel chat:
1 |
PUBSUB NUMSUB chat |
To seen umber of subscriptions to patterns (that are performed using the PSUBSCRIBE command), use PUBSUB NUMPAT
ACL
Stands for Access Control List, allows certain connections to be limited in terms of the commands that can be executed and the keys that can be accessed. The way it works is that, after connecting, a client is required to authenticate providing a username and a valid password
Setting Username and Password
this will set password temporarily (until redis or server restart)
CONFIG SET requirepass mypass
CONFIG GET requirepass
AUTH <username> <password>
Client Connections
To get information about clients and also managing them (i.e . killing, tracking etc) you can use CLIENT command:
Returns information and statistics about the client connections
1 |
CLIENT LIST |
Returns information and statistics about the current client
1 |
CLIENT INFO |
When tracking is enabled Redis remembers the keys that the connection requested, in order to send later invalidation messages when such keys are modified. (side caching)
1 |
CLIENT TRACKING ON|OFF |
Example:
- Client 1
->
Server: CLIENT TRACKING ON - Client 1
->
Server: GET foo - (The server remembers that Client 1 may have the key “foo” cached)
- (Client 1 may remember the value of “foo” inside its local memory)
- Client 2
->
Server: SET foo SomeOtherValue - Server
->
Client 1: INVALIDATE “foo”
Notifications
Keyspace notifications enable clients to subscribe to Pub/Sub channels to receive events that impact the Redis data set in some way. Due to performance issue Keyspace notifications are disabled by default.
There are two types of Keyspace notifications: keyspace (what sort of event is happening to a key) and keyevent (what happened to a specific key).
For instance a DEL operation, could be done with the following PUBLISH commands
PUBLISH __keyspace@<db_number>__:<your-key> del
PUBLISH __keyevent@<db_number>__:del <your-key>
Now let’s have a complete example, first enabling the notifications:
CONFIG SET notify-keyspace-events AKE
1 |
CONFIG SET notify-keyspace-events AKE |
“AKE” string means all the events except “m” (Key miss events- events generated when a key that doesn’t exist is accessed).
A
: Alias for “g$lshztxe” (means all the events except “m”)
E
: Keyevent events, published with __keyevent@__
prefix.
K
: Keyspace events, published with __keyspace@__
prefix.
Now let’s subscribe to delete events on keys:
1 |
SUBSCRIBE __keyevent@0__:del |
Now if we delete a key, we are able to see the deletion event:
1 |
DEL hello |
Another example would be all events on all keys on all databases:
1 |
PSUBSCRIBE '__key*__:*' |
Another example, lets make the key greeting with the value of hello that expires in 10 seconds:
1 |
SETEX greeting 20 hello |
You should be able to see the event with PSUBSCRIBE '__key*__:*'