Redis Quick Start

After installing Redis, let's get started quickly and learn basic Redis operations.

Starting the Redis Server

Foreground Startup

The simplest way to start Redis — it runs in the foreground and logs directly to the terminal.

BASH
redis-server

Output:

TEXT
                _._
           _.-``__ ''-._
      _.-``    `.  `_.  ''-._
  _.-`` .-`` .-```.  ```.-''  ''-._
.-`` .-`` .-`````-..-'''.-''      ''-._
( '      .       ''-.             ``.
|`.    `-.   `-.    `-.  `-.        `-.)
|  `-.    `-.    `-.    `-.    `-.    `'
 `-.   `-.    `-.    `-.    `-.    `-.    _
     `-.    `-.    `-.    `-.    `-.  .-'
         `-.    `-.    `-.    `-.  .-'
             `-.    `-.    `-.  .-'
                 `-.    `-.  .-'
                     `-.  .-'
                         `-

Redis 7.0.11 (00000000/0) 64 bit
Running in standalone mode
Port: 6379
PID: 12345
Ready to accept connections
💡 Tip: Press Ctrl+C to stop the Redis server.

Background Startup

Running in the background is recommended for production environments.

BASH
# Method 1: Use daemonize parameter
redis-server --daemonize yes

# Method 2: Edit config file
# Edit /etc/redis/redis.conf
daemonize yes
# Then start
redis-server /etc/redis/redis.conf

Start on a Specific Port

BASH
# Use port 6380
redis-server --port 6380

Check if Redis is Running

BASH
# Linux
ps aux | grep redis-server

# Or use redis-cli
redis-cli ping
# Returns PONG if Redis is running

Connecting to Redis

Using redis-cli

redis-cli is Redis's built-in command-line client.

BASH
# Connect to local Redis (default 127.0.0.1:6379)
redis-cli

# After connecting, the prompt changes to:
127.0.0.1:6379>

Specifying Host and Port

BASH
# Connect to a specific host and port
redis-cli -h 192.168.1.100 -p 6379

# Connect to a different local port
redis-cli -p 6380

Connecting with a Password

BASH
# Method 1: Command-line argument
redis-cli -a yourpassword

# Method 2: Authenticate after connecting
redis-cli
 AUTH yourpassword
OK
⚠️ Security warning: Using the -a parameter exposes the password in command history. For production, use the AUTH command or config file instead.

Connecting via Unix Socket

BASH
redis-cli -s /tmp/redis.sock

Exiting redis-cli

BASH
# Exit the connection
 exit
# or
 quit
# or press Ctrl+D

First Command: PING

The PING command tests whether the connection is working, similar to the network ping command.

Example: Test Connection

BASH
PING
▶ Try it Yourself

If Redis is working properly, it returns PONG.

PING with a Message

REDIS
 PING "Hello"
"Hello"

PING can carry a message, and Redis returns it as-is.

💡 Use case: PING is commonly used for health checks, connection testing, and measuring network latency.

Basic Commands: SET and GET

SET and GET are the most commonly used commands for storing and retrieving string data.

SET: Store Data

The SET command sets a key-value pair.

Example: Basic SET

BASH
SET name "Redis Tutorial"
GET name
▶ Try it Yourself

Example: With Expiration

BASH
# Set a key that expires in 10 seconds
SET temp "temporary" EX 10
GET temp

# Or use PX for milliseconds
SET temp2 "temp" PX 5000
GET temp2
▶ Try it Yourself

Example: Set Only When Key Doesn't Exist

BASH
# NX: Only set if key does not exist
SET name "New Name" NX

# XX: Only set if key exists
SET name "Updated Name" XX
GET name
▶ Try it Yourself

SET Command Full Syntax

SET key value [NX|XX] [GET] [EX seconds|PX milliseconds|EXAT timestamp|PXAT timestamp]
Parameter Description
NX Only set if key does not exist
XX Only set if key exists
GET Return the old value (Redis 6.2+)
EX seconds Set expiration in seconds
PX milliseconds Set expiration in milliseconds
EXAT timestamp Set expiration Unix timestamp (seconds)
PXAT timestamp Set expiration Unix timestamp (milliseconds)

GET: Read Data

The GET command retrieves the value of a key.

Example: Basic GET

BASH
GET name

# Key doesn't exist, returns nil
GET notexist
▶ Try it Yourself

Example: GETSET (Get Old Value, Set New Value)

BASH
GETSET name "New Value"
GET name
▶ Try it Yourself

Other Basic Commands

DEL: Delete a Key

REDIS
 SET temp "delete me"
OK

 DEL temp
(integer) 1  # Deletion successful, returns number of deleted keys

 DEL temp
(integer) 0  # Key doesn't exist, 0 deleted

EXISTS: Check if Key Exists

REDIS
 SET name "Redis"
OK

 EXISTS name
(integer) 1  # Exists

 EXISTS notexist
(integer) 0  # Doesn't exist

KEYS: Find Keys

REDIS
# Set some test data
 SET user:1 "Alice"
 SET user:2 "Bob"
 SET product:1 "iPhone"

# Find all keys (use with caution!)
 KEYS *
1) "user:1"
2) "user:2"
3) "product:1"
4) "name"

# Find keys matching a pattern
 KEYS user:*
1) "user:1"
2) "user:2"

 KEYS *:1
1) "user:1"
2) "product:1"
⚠️ Warning: The KEYS command scans the entire database. It is very slow with large datasets and should be avoided in production! Use SCAN instead.

FLUSHDB: Clear Current Database

REDIS
# Clear all data in the current database (dangerous!)
 FLUSHDB
OK
⚠️ Danger: FLUSHDB deletes all data. Use with extreme caution in production!

DBSIZE: Count Keys

REDIS
 DBSIZE
(integer) 4  # The current database has 4 keys

Command Return Types

Redis commands return different types of results:

Return Example Type Description
OK Simple string Operation successful
"value" String String value
(integer) 1 Integer Numeric result
1) "a"
2) "b"
Array List or set
(nil) Null Key doesn't exist or no result
# Error Error Command execution failed

Batch Executing Commands

Interactive Mode

Enter commands one by one in redis-cli:

REDIS
 SET a 1
OK
 SET b 2
OK
 GET a
"1"

Pipeline Mode

Execute commands from a file in batch:

BASH
# Create a command file commands.txt
echo "SET key1 value1" > commands.txt
echo "SET key2 value2" >> commands.txt
echo "GET key1" >> commands.txt

# Execute batch
cat commands.txt | redis-cli

Output:

TEXT
OK
OK
"value1"

Direct Command-Line Execution

BASH
# Execute a single command directly
redis-cli SET mykey "myvalue"
# Output: OK

redis-cli GET mykey
# Output: "myvalue"

# Execute multiple commands
redis-cli << EOF
SET a 1
SET b 2
GET a
GET b
EOF

Using the Help System

Redis has a built-in comprehensive help system.

View Command Help

REDIS
 HELP SET

  SET key value [NX|XX] [GET] [EX seconds|PX milliseconds|EXAT unix-time-seconds|PXAT unix-time-milliseconds|KEEPTTL]
  summary: Set the string value of a key
  since: 1.0.0
  group: string

View Command Groups

REDIS
 HELP @string
# Lists all string commands

Tab Completion

redis-cli supports Tab key for command completion:

REDIS
 SET<press Tab>
# Auto-completes to SET

Useful Tips

1. View Server Info

REDIS
 INFO
# Returns extensive server information

# View specific sections
 INFO server
 INFO memory
 INFO stats

2. View Configuration

REDIS
# View all config
 CONFIG GET *

# View specific config
 CONFIG GET maxmemory
1) "maxmemory"
2) "0"

3. Monitor Commands

REDIS
# Real-time monitoring of all executed commands
 MONITOR
OK
# Then displays all commands from all clients
💡 Use case: MONITOR is useful for debugging — you can see all client commands. Use with caution in production (performance impact).

4. View Client Connections

REDIS
 CLIENT LIST
id=1 addr=127.0.0.1:52345 fd=8 name= age=10 idle=0 ...

❓ FAQ

Q Can't connect with redis-cli?
A Check if Redis is running (ps aux | grep redis), verify the port is correct, and check firewall settings.
Q Why does it return (nil)?
A (nil) means null — usually because the key doesn't exist. Use EXISTS to check.
Q How do I clear test data?
A Use FLUSHDB to clear the current database, or FLUSHALL to clear all databases (dangerous!).
Q How do I view all keys? *A: Use KEYS , but this is slow with large datasets. Use SCAN in production.

Q: How do I exit redis-cli?

A Type exit or quit, or press Ctrl+D.

📖 Summary

  • redis-server starts the Redis server, redis-cli connects to it
  • PING tests the connection, SET/GET stores and retrieves strings
  • DEL deletes keys, EXISTS checks if a key exists
  • KEYS finds keys (caution in production), DBSIZE counts keys
  • Use HELP for command help, Tab key for completion
  • MONITOR watches commands, INFO shows server info

📝 Exercises

  1. Startup practice: Start the Redis server, connect with redis-cli, and run the PING command
  2. Basic operations: Use SET to store your name and age, then use GET to retrieve them
  3. Expiration practice: Set a key with expiration, wait for it to expire, then use GET to verify
  4. Batch operations: Create a text file with multiple Redis commands and execute them using pipeline mode

Next Lesson

In the next lesson, we will learn Redis Configuration, covering the Redis config file and common configuration options.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏