Introduction to Redis Architecture, Installation, and Data Operations

SQL vs. NoSQL Database Characteristics

FeatureSQL DatabasesNoSQL Databases
Storage ModelRelational tables with fixed schemasFlexible structures (Key-Value, Document, Column-family, Graph, Time-series)
ScalabilityVertical (upgrading single hardware)Horizontal (adding more server nodes)
TransactionsACID compliant, high consistencyBASE oriented, eventual consistency
ExamplesPostgreSQL, MySQL, OracleRedis, MongoDB, Cassandra, ElasticSearch

Redis Overview

Redis (Remote Dictionary Server) is an open-source, in-memory data structure store implemented in C. It functions as a database, cache, and message broker. It uses a key-value storage model and is a critical component in modern distributed architectures.

Redis operates primarily using a single-threaded process model for command execution. While it is possible to run multiple Redis instances on a single physical server to handle higher concurrency, this increases CPU load. In production environments, the decision to run single or multiple instances depends on the specific concurrency requirements and available CPU resources.

Core Advantages

  • High Performance: Achieves up to 110,000 reads and 81,000 writes per second.
  • Rich Data Types: Supports Strings, Lists, Hashes, Sets, Sorted Sets, and more.
  • Persistence: Supports saving in-memory data to disk for recovery.
  • Atomic Operations: All individual commands are atomic.
  • Replication: Supports Master-Slave replication for data backup and high availability.

Common Use Cases

Redis is ideal for scenarios requiring high throughput and low latency, such as Session caching, Message Queues, Leaderboards, Counters, Real-time analytics, and Pub/Sub systems.

Data suitable for caching includes:

  • Real-time data: Information requiring immediate updates (e.g., live logistics status).
  • Weak consistency tolerance: Data where a slight delay in propagation is acceptable (e.g., store location updates).
  • High read frequency, low write frequency: Content like homepage advertisements.

Performance Drivers

  1. In-Memory Storage: Eliminates disk I/O latency.
  2. Single-Threaded Core: Avoids context switching overhead and lock contention (deadlocks), reducing CPU consumption.
  3. I/O Multiplexing: Efficiently handles multiple concurrent network connections.

Note: While Redis 6.0 introduced multi-threading for network I/O, command execution remains single-threaded.

Installation and Configuration

# System Preparation
systemctl stop firewalld
systemctl disable firewalld
setenforce 0
sed -i 's/enforcing/disabled/' /etc/selinux/config

# Kernel Optimization
echo "vm.overcommit_memory = 1" >> /etc/sysctl.conf
echo "net.core.somaxconn = 2048" >> /etc/sysctl.conf
sysctl -p

# Compile from Source
yum install -y gcc gcc-c++ make
tar -zxvf /opt/redis-7.0.9.tar.gz -C /opt/
cd /opt/redis-7.0.9
make
make PREFIX=/usr/local/redis install

# Setup Directories and Permissions
mkdir -p /usr/local/redis/{conf,log,data}
cp /opt/redis-7.0.9/redis.conf /usr/local/redis/conf/
useradd -M -s /sbin/nologin redis
chown -R redis.redis /usr/local/redis/

# Configure Environment Variables
echo 'export PATH=$PATH:/usr/local/redis/bin' >> /etc/profile
source /etc/profile

# Configuration Tuning (/usr/local/redis/conf/redis.conf)
# bind 127.0.0.1 192.168.50.102
# protected-mode no
# port 6379
# daemonize yes
# pidfile /usr/local/redis/log/redis_6379.pid
# logfile "/usr/local/redis/log/redis_6379.log"
# dir /usr/local/redis/data
# requirepass your_secure_password

# Systemd Service Configuration
cat > /usr/lib/systemd/system/redis-server.service << EOF
[Unit]
Description=Redis Server
After=network.target

[Service]
User=redis
Group=redis
Type=forking
PIDFile=/usr/local/redis/log/redis_6379.pid
ExecStart=/usr/local/redis/bin/redis-server /usr/local/redis/conf/redis.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

# Start Service
systemctl daemon-reload
systemctl start redis-server
systemctl enable redis-server

Command Line Utilities

  • redis-server: Starts the Redis server.
  • redis-cli: Command-line interface for client interaction.
  • redis-benchmark: Utility for performance testing.
  • redis-check-aof/rdb: Tools for repairing persistence files.
# Connection Syntax
# redis-cli -h <host> -p <port> -a <password>

# Performance Test Example
redis-benchmark -h 192.168.50.102 -p 6379 -c 100 -n 100000

Database Operations (CRUD)

# Basic Key-Value Operations
SET username "admin"
GET username

# Key Management
KEYS *              # List all keys
KEYS user*          # List keys matching pattern
EXISTS key_name     # Check if key exists (returns 1 or 0)
DEL key_name        # Delete specific key
TYPE key_name       # Return data type of key

# Expiration Management
EXPIRE session_id 3600   # Set expiry in seconds
TTL session_id           # Check remaining time to live (-1: permanent, -2: expired)
SETEX temp_token 60 "value" # Set value with expiry

# Renaming Keys
RENAME old_key new_key   # Rename (overwrites target)
RENAMENX old_key new_key # Rename only if new_key does not exist

# Database Statistics
DBSIZE              # Count keys in current database

Multi-Database Management

Redis provides 16 databases indexed 0 to 15, isolated from each other.

SELECT 1            # Switch to database 1
MOVE key_name 2     # Move key to database 2

FLUSHDB             # Clear current database
FLUSHALL            # Clear all databases (Use with caution)

Data Types and Syntax Cheat Sheet

# String
SET key value
GET key
DEL key

# List
LPUSH list_name val1 val2
LRANGE list_name 0 -1
LREM list_name count value

# Hash
HSET hash_name field1 val1
HGET hash_name field1
HGETALL hash_name
HDEL hash_name field1

# Set
SADD set_name val1 val2
SMEMBERS set_name
SREM set_name val1

# Sorted Set
ZADD zset_name 1 member1
ZRANGE zset_name 0 -1 WITHSCORES
ZREMRANGEBYRANK zset_name 0 1

Tags: Redis NoSQL database Caching installation

Posted on Tue, 18 Aug 2026 16:52:48 +0000 by szz