Skip to content

Redis🔗

Back

Installation🔗

Debain/Ubuntu

sudo apt update
sudo apt install redis-server

# check status
sudo systemctl status redis

macOS

brew install redis
brew service start redis

Setup🔗

Access Redis CLI : Connect to redis server🔗

redis-cli

Test Connection🔗

ping # server replies: PONG

Set and Get Data: storing and retrieving key-value pairs🔗

SET mykey "Hello Redis"  
GET mykey 

Enabling Persistence🔗

Edit /etc/redis/redis.conf

  • For RDB (snapshotting)
save 900 1  # Save if 1 key changes in 900 seconds  
save 300 10 # Save if 10 keys change in 300 seconds
  • For AOF (Append Only File)
appendonly yes  
appendfilename "appendonly.aof" 

Restart Redis

sudo systemctl restart redis

Security🔗

1. Set a Password🔗

Edit /etc/redis/redis.conf

requirepass yourpassword
sudo systemctl restart redis
# Authenticate in redis-cli
AUTH yourpassword

2. Bind to Specific IP🔗

Edit /etc/redis/redis.conf

bind 127.0.0.1

3. Disable Dangerous Commands🔗

rename-command FLUSHALL ""

4. Enable Firewall🔗

sudo ufw allow from 192.168.1.0/24 to any port 6379  

Essential Commands🔗

# set a key
SET mykey "Hello Redis"

# get a key
GET mykey

# delete a key
DEL mykey

# check if exists
EXISTS mykey

Data Types🔗

  • Lists

    LPUSH mylist "item1"  
    RPUSH mylist "item2"  
    LRANGE mylist 0 -1  
    
  • Sets

    SADD myset "item1"  
    SMEMBERS myset  
    
  • Hashes

    HSET myhash field1 "value1"  
    HGET myhash field1 
    
  • Sorted Sets

    ZADD myzset 1 "item1"  
    ZRANGE myzset 0 -1  
    

Server Management🔗

# flush all data
FLUSHALL

# get server info
INFO

# monitor commands
MONITOR

Advanced Features🔗

Pub/Sub Messaging🔗

# publisher
PUBLISH mychannel "Hello"  

# sub
SUBSCRIBE mychannel

Transactions🔗

Use MULTI and EXEC for atomic operations

MULTI  
SET key1 "value1"  
SET key2 "value2"  
EXEC  

Lua Scripting🔗

EVAL "return redis.call('GET', 'mykey')" 0

Troubleshooting🔗

# view redis logs
sudo tail -f /var/log/redis/redis-server.log  

# test connection
redis-cli -h 127.0.0.1 -p 6379 ping  

# check memory usage
INFO memory

Tips🔗

# using redis as a cache
SET mykey "value" EX 60

# backup data using SAVE or BGSAVE to create snapshots
SAVE

# monitoring performance using redis-benchmark
redis-benchmark -n 100000 -c 50