Featured image of post Redis Cheatsheet

Redis Cheatsheet

Redis tips and tricks

Motivation

Recently, I maintain services that use Redis frequently for caching. It is very interesting since the services handle millions of messages a day. Before using Redis on the application, it is good to know what Redis is and how to use it.

Installation

Basically, I have written how to install Redis using docker in this article. Now, I’ll explain more detail how to install the Redis with its configuration from official docker image (https://hub.docker.com/_/redis).

Basic Container

Redis can be installed in various ways. But docker is my preferred one.

1
docker run --name redis-container-name -p 6379:6379 -d redis

This command will do the following:

  1. Pull the latest image from the docker hub
  2. Create and run the container and name it: my-redis
  3. Route port 6379 on my laptop to port 6379 inside the container. 6379 is Redis default port and can be changed

source: Medium

To enter terminal on Redis container, use

1
docker exec -it redis-container-name /bin/bash

And use redis-cli -h localhost to use command line interface. Run redis-cli --help to see what kind of command that you can use.

With Volume

1
docker run --name redis_container -v /path/to/local/data:/usr/local/etc/redis -p 6379:6379 -d redis

This command will do the same as previous but it mount local folder in /path/to/local/data to container folder /usr/local/etc/redis. Volume can be used to mount Redis configuration file. The configuration file by default can be accessed in this github link (https://github.com/redis/redis/blob/6.0/redis.conf). From the link, you can switch any version of Redis that you want to use.

1
docker run -v /myredis/conf:/usr/local/etc/redis --name redis-container redis redis-server /usr/local/etc/redis/redis.conf

Config Example

In this section, I put some examples taken from PZN channel on YouTube. To follow these sections you need to clone my github repository containing docker-compose of Redis example:

1
git clone https://github.com/aysf/example.git $HOME/docker/example  

I put the example on my preferred folder ~/docker/example but you can put anywhere you like.

Note: everytime you run up a redis container with config, please make sure that config installed properly by command docker logs redis-container-name. If it’s installed correctly, there will be a Redis logo on your terminal screen.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
1:C 16 Jul 2022 03:50:12.515 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
1:C 16 Jul 2022 03:50:12.516 # Redis version=6.2.7, bits=64, commit=00000000, modified=0, pid=1, just started
1:C 16 Jul 2022 03:50:12.516 # Configuration loaded
1:M 16 Jul 2022 03:50:12.517 * monotonic clock: POSIX clock_gettime
1:M 16 Jul 2022 03:50:12.518 # A key '__redis__compare_helper' was added to Lua globals which is not on the globals allow list nor listed on the deny list.
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 6.2.7 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                  
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 1
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           https://redis.io       
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

1:M 16 Jul 2022 03:50:12.518 # Server initialized
1:M 16 Jul 2022 03:50:12.519 * Ready to accept connections

With Command

We will use Redis feature called pipeline to run command from the terminal Linux/Unix. To start, run the cloned docker compose example.

1
docker-compose -f $HOME/docker/example/redis/redis-with-command/docker-compose.yaml up -d  

The docker-compose.yaml looks like

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
version: '3.5'

services:
  redis:
    container_name: redis-with-command
    image: redis:6
    command: redis-server /usr/local/etc/redis/redis.conf
    ports:
      - 6379:6379
    volumes:
      - ./config/redis.conf:/usr/local/etc/redis/redis.conf
      - ./command:/usr/local/etc/command

This docker-compose.yaml create container with two volumes, for config file and command file.
Enter to the container terminal docker exec -it redis-with-command /bin/bash and run

1
cat /usr/local/etc/command/sets.txt | redis-cli -h localhost --pipe

With Security

We will enable security, therefore client we’ll require to provide username and password to access the database.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
version: '3.5'

services:
  redis:
    container_name: redis-with-security
    image: redis:6
    command: redis-server /usr/local/etc/redis/redis.conf
    ports:
      - 6379:6379
    volumes:
      - ./config/redis.conf:/usr/local/etc/redis/redis.conf
  redis-client:
    container_name: redis-client
    image: redis:6

This docker-compose create two container in order to simulate client that would access to server with security. Let’s run the yaml file

1
docker-compose -f $HOME/docker/example/redis/redis-with-security/docker-compose.yaml up -d  

Now, Enter to Redis server and try to ping from redis-cli

1
2
3
4
5
% docker exec -ti redis-with-security /bin/bash
root@90d37981271e:/data# redis-cli
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> 

See that you can ping redis from it’s own machine.

Next, use the client container to login..

1
% docker exec -it redis-client /bin/bash

and enter redis-cli server from client using command redis-cli -h redis-with-security. Then, you’ll get a rejection !

1
Could not connect to Redis at redis-with-security:6379: Connection refused

To solve this problem, commented out this line (line number 5) on the config file

1
2
3
4
5
6
...
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
# JUST COMMENT THE FOLLOWING LINE.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# bind 127.0.0.1
...

Then reset these redis containers by docker-compose down and docker-compose up -d. Again, enter to the terminal of client container and run redis-cli -h redis-with-security. You shall be succed enter the redis-cli but you still get an error once you try to ping from the cli.

Error Redis Authentication

As you see on the error message, you need to set protected-mode no so you can do ping command from cli.

With Authentication

Disabling protected-mode is not recomended when you build real apps. We should use authentication instead. Put this setting on redis.conf file.

1
2
3
4
5
6
7
8
9
...
# Basically ACL rules are processed left-to-right.
#
# For more information about ACL configuration please refer to
# the Redis web site at https://redis.io/topics/acl

user default on +@connection
user foo on +@all ~* >yourcustompassword
...

Then run docker-compose -f $HOME/Docker/example/redis/redis-with-acl/docker-compose.yaml up -d. The default user setting above should be added to because, at first time on cli mode, the ‘default’ user need to have authorization for connection.

Try again enter cli mode, put username and password authentication… and do ping!

1
2
3
4
5
6
root@aaf906b99c21:/data# redis-cli -h redis-with-acl
redis-with-acl:6379> auth foo yourcustompassword
OK
redis-with-acl:6379> ping
PONG
redis-with-acl:6379> 

And tada… we can ‘ping’ without disabliing ‘protected-mode’. You can ensure it by using command config get <pattern>

1
2
3
redis-with-acl:6379> config get 'protected-mode'
1) "protected-mode"
2) "yes"

Redis GUI

These are some free Redis GUIs that you can try (stats updated 15 July 2022):

  1. AnotherRedisDesktopManager: Star 21.6k
  2. RedisDesktopManager: Star 20.5k
  3. redis-commander: Star 3k
  4. QuickRedis: Star 1.3k
  5. P3X Redis UI: Star 522
  6. redis-gui: Star 338

Redis Data Type

Basic

There are three types of Redis data type

  • Strings
  • Lists
  • Hash

Strings

Strings are the most basic kind of Redis value. Redis strings are binary safe, this means that a Redis string can contain any kind of data, for instance a JPEG image or a serialized Ruby object. A string value can be at max 512 Megabytes in length (https://redis.io/docs/manual/data-types/#strings).

The strings command can be found here, https://redis.io/commands/?group=string. These are some method on strings:

  • The commond method for caching are GET, MGET, SET, MSET. It is possible to cache text or binary data in Redis, which could be anything from HTML pages and API responses to images and videos.
  • for cache with automation expiration: SETEX, EXPIRE, EXPIREAT. This is very useful when database queries take a long time to run and can be cached for a given period time. Consequently, this avoids running those queries too frequently.
  • for counting: INCR and INCRBY. Good examples of counters are page views, video views and like.

Lists

Redis Lists are simply lists of strings, sorted by insertion order. It is possible to add elements to a Redis List pushing new elements on the head (on the left) or on the tail (on the right) of the list (https://redis.io/docs/manual/data-types/#lists).

Hashes

Redis Hashes are maps between string fields and string values, so they are the perfect data type to represent objects (e.g. A user with a number of fields like name, surname, age, and so forth)

Advance

  • Sets
  • Sorted Sets
  • Bitmaps
  • HyperLogLogs

Sets

Redis sets an unordered collection of Strings. It is possible to add, remove, and test for existence of members in O(1)

Sorted Sets

Time Series

Commands

Pub/Sub

Transaction

Scripting

Miscellaneous Commands


References:

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy