Redis - In-Memory Data Store
Redis is an open-source, in-memory data structure store, used as a database, cache, message broker, and streaming engine.
GitHub
https://github.com/redis/redis
What is Redis?
Redis provides:
Key Features
1. Performance
2. Data Structures
3. Features
Installation
macOS
text
ash
brew install redis
brew services start redis
Linux (Ubuntu/Debian)
text
ash
sudo apt-get update
sudo apt-get install redis-server
sudo systemctl start redis
Docker
text
ash
docker run -d -p 6379:6379 redis
Basic Commands
String Operations
text
ash
# Set value
SET user:1 "John"
# Get value
GET user:1
# Set with expiration (10 seconds)
SETEX session:123 10 "data"
# Delete
DEL user:1
List Operations
text
ash
# Push to list
LPUSH queue:1 "task1"
RPUSH queue:1 "task2"
# Get list range
LRANGE queue:1 0 -1
# Pop from list
LPOP queue:1
RPOP queue:1
Set Operations
text
ash
# Add to set
SADD tags:1 "python" "redis" "database"
# Get all members
SMEMBERS tags:1
# Check membership
SISMEMBER tags:1 "python"
# Remove from set
SREM tags:1 "python"
Hash Operations
text
ash
# Set field
HSET user:1 name "John"
HSET user:1 email "john@example.com"
# Get field
HGET user:1 name
# Get all fields
HGETALL user:1
# Delete field
HDEL user:1 email
Sorted Sets
text
ash
# Add with score
ZADD leaderboard 100 "player1"
ZADD leaderboard 200 "player2"
ZADD leaderboard 150 "player3"
# Get range
ZRANGE leaderboard 0 -1
# Get with scores
ZRANGE leaderboard 0 -1 WITHSCORES
# Get by score range
ZRANGEBYSCORE leaderboard 100 200
Advanced Features
Transactions
text
ash
MULTI
SET user:1 "Alice"
GET user:1
EXEC
Expiration
text
ash
# Set expiration (in seconds)
EXPIRE key 60
# Set expiration (in milliseconds)
PEXPIRE key 60000
# Set key with expiration
SETEX key 60 "value"
# Get remaining TTL
TTL key
Pub/Sub
text
ash
# Subscribe
SUBSCRIBE channel1
# Publish
PUBLISH channel1 "Hello"
# Pattern subscription
PSUBSCRIBE news.*
Programming Languages
Python
text
python
import redis
# Connect
r = redis.Redis(host='localhost', port=6379, db=0)
# Set and get
r.set('key', 'value')
value = r.get('key')
# List operations
r.lpush('mylist', 'item1')
items = r.lrange('mylist', 0, -1)
# Hash operations
r.hset('user:1', mapping={'name': 'John', 'age': 30})
user = r.hgetall('user:1')
JavaScript/Node.js
text
javascript
const redis = require('redis');
// Connect
const client = redis.createClient();
await client.connect();
// Set and get
await client.set('key', 'value');
const value = await client.get('key');
// List operations
await client.lPush('mylist', 'item1');
const items = await client.lRange('mylist', 0, -1);
Go
text
go
import "github.com/go-redis/redis/v8"
// Connect
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
// Set and get
err := client.Set(ctx, "key", "value", 0).Err()
val, err := client.Get(ctx, "key").Result()
Use Cases
1. Caching
text
python
# Cache expensive database query
cache_key = f"user:{user_id}"
cached = r.get(cache_key)
if not cached:
# Fetch from database
user = db.get_user(user_id)
# Cache for 1 hour
r.setex(cache_key, 3600, json.dumps(user))
else:
user = json.loads(cached)
2. Session Store
text
python
# Store session data
session_id = "abc123"
r.setex(f"session:{session_id}", 3600, json.dumps({
'user_id': 1,
'username': 'john'
}))
3. Rate Limiting
text
python
# Limit API calls
def rate_limit(user_id, limit=100, window=60):
key = f"rate:{user_id}"
count = r.incr(key)
if count == 1:
r.expire(key, window)
return count <= limit
4. Leaderboard
text
python
# Add score
r.zadd('leaderboard', {'player1': 100})
# Get top 10
top_players = r.zrange('leaderboard', 0, 9, desc=True)
5. Message Queue
text
python
# Producer
r.lpush('task_queue', json.dumps({'task': 'send_email', 'to': 'user@example.com'}))
# Consumer
while True:
task = r.brpop('task_queue')
process_task(json.loads(task[1]))
Performance Tips
Persistence Options
RDB (Snapshot)
text
ash
# Save every 5 minutes if at least 1 key changed
save 300 1
# Save every 1 minute if at least 1000 keys changed
save 60 1000
AOF (Append Only File)
text
ash
# Enable AOF
appendonly yes
# Append every second (default)
appendfsync everysec
Security
text
ash
# Set password
requirepass yourpassword
# Bind to specific address
bind 127.0.0.1
# Rename dangerous commands
rename-command FLUSHDB ""
rename-command FLUSHALL ""
Monitoring
text
ash
# CLI monitor
redis-cli monitor
# Get info
redis-cli info
# Check latency
redis-cli --latency
# Memory analysis
redis-cli --bigkeys
Why Redis?
Alternatives
| Feature | Redis | Memcached | Hazelcast |
|---------|-------|-----------|-----------|
| Persistence | Yes | No | Yes |
| Data Types | Rich | Simple | Rich |
| Clustering | Yes | No | Yes |
| Memory Usage | Optimized | High | High |
Summary
Redis is an essential tool for any modern application. Whether you need caching, session management, messaging, or real-time data processing, Redis delivers exceptional performance and versatility.
Rating: 猸愨瓙猸愨瓙猸?
Best for: Caching, sessions, real-time data
Learning curve: 猸愨瓙
Performance: 猸愨瓙猸愨瓙猸?
💬 评论区 (0)
暂无评论,快来抢沙发吧!