Azure Cache for Redis #

什么是 Azure Cache for Redis? #

Azure Cache for Redis 是基于 Redis 软件的托管缓存服务,提供高性能数据存储。

text
┌─────────────────────────────────────────────────────────────┐
│                    Redis 缓存概览                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  特点                                                        │
│  ├── 高性能:亚毫秒级延迟                                   │
│  ├── 托管服务:无需管理                                     │
│  ├── 高可用:内置冗余                                       │
│  ├── 安全:VNet 和加密                                      │
│  └── 可扩展:动态扩展                                       │
│                                                             │
│  支持的数据结构                                              │
│  ├── Strings: 字符串                                        │
│  ├── Lists: 列表                                            │
│  ├── Sets: 集合                                             │
│  ├── Sorted Sets: 有序集合                                  │
│  ├── Hashes: 哈希表                                         │
│  └── Streams: 流                                            │
│                                                             │
│  适用场景                                                    │
│  ├── 数据缓存                                               │
│  ├── 会话存储                                               │
│  ├── 消息队列                                               │
│  ├── 排行榜                                                 │
│  └── 实时分析                                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

服务层级 #

层级对比 #

text
┌─────────────────────────────────────────────────────────────┐
│                    服务层级                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  基本 (Basic)                                                │
│  ├── 单节点                                                 │
│  ├── 无 SLA                                                 │
│  ├── 开发测试                                               │
│  └── 成本最低                                               │
│                                                             │
│  标准 (Standard)                                             │
│  ├── 双节点(主/从)                                        │
│  ├── 99.9% SLA                                              │
│  ├── 自动故障转移                                           │
│  └── 生产环境                                               │
│                                                             │
│  高级 (Premium)                                              │
│  ├── 多节点集群                                             │
│  ├── 99.99% SLA                                             │
│  ├── VNet 注入                                              │
│  ├── 持久化                                                 │
│  └── 企业级应用                                             │
│                                                             │
│  企业 (Enterprise)                                           │
│  ├── Redis Enterprise                                       │
│  ├── 最高性能                                               │
│  ├── 模块支持                                               │
│  └── 企业功能                                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

层级功能对比 #

功能 基本 标准 高级 企业
SLA 99.9% 99.99% 99.99%
集群
持久化
VNet
模块

创建 Redis 缓存 #

使用 Azure CLI #

bash
# 创建资源组
az group create --name myResourceGroup --location eastus

# 创建基本缓存
az redis create \
  --resource-group myResourceGroup \
  --name myCache \
  --location eastus \
  --sku Basic \
  --vm-size c0

# 创建标准缓存
az redis create \
  --resource-group myResourceGroup \
  --name myStandardCache \
  --location eastus \
  --sku Standard \
  --vm-size c1

# 创建高级缓存
az redis create \
  --resource-group myResourceGroup \
  --name myPremiumCache \
  --location eastus \
  --sku Premium \
  --vm-size p1 \
  --shard-count 2

使用 Azure 门户 #

text
┌─────────────────────────────────────────────────────────────┐
│                    创建 Redis 缓存步骤                       │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  步骤 1: 基本信息                                            │
│  ├── DNS 名称                                               │
│  ├── 订阅选择                                               │
│  ├── 资源组选择/创建                                        │
│  └── 区域选择                                               │
│                                                             │
│  步骤 2: 定价层                                              │
│  ├── 服务层级                                               │
│  ├── 缓存大小                                               │
│  └── 集群配置(高级)                                       │
│                                                             │
│  步骤 3: 网络                                                │
│  ├── 连接方式:公网/私有                                    │
│  └── VNet 配置                                              │
│                                                             │
│  步骤 4: 高级                                                │
│  ├── 持久化                                                 │
│  ├── 集群                                                   │
│  └── 数据持久化                                             │
│                                                             │
└─────────────────────────────────────────────────────────────┘

连接 Redis #

获取连接信息 #

bash
# 获取缓存信息
az redis show \
  --resource-group myResourceGroup \
  --name myCache \
  --query "{host:hostName,port:port,sslPort:sslPort}"

# 获取访问密钥
az redis list-keys \
  --resource-group myResourceGroup \
  --name myCache

使用 Redis CLI #

bash
# 连接 Redis
redis-cli -h myCache.redis.cache.windows.net \
  -p 6380 \
  -a <access-key> \
  --tls

# 基本操作
SET mykey "Hello"
GET mykey
DEL mykey

应用程序连接 #

javascript
// Node.js 使用 redis 库
const redis = require('redis');

const client = redis.createClient({
  socket: {
    host: 'myCache.redis.cache.windows.net',
    port: 6380,
    tls: true
  },
  password: '<access-key>'
});

await client.connect();

// 基本操作
await client.set('mykey', 'Hello');
const value = await client.get('mykey');
console.log(value); // "Hello"
csharp
// C# 使用 StackExchange.Redis
using StackExchange.Redis;

var config = new ConfigurationOptions
{
    EndPoints = { "myCache.redis.cache.windows.net:6380" },
    Password = "<access-key>",
    Ssl = true
};

var connection = ConnectionMultiplexer.Connect(config);
var db = connection.GetDatabase();

// 基本操作
db.StringSet("mykey", "Hello");
string value = db.StringGet("mykey");
python
# Python 使用 redis-py
import redis

r = redis.Redis(
    host='myCache.redis.cache.windows.net',
    port=6380,
    password='<access-key>',
    ssl=True
)

# 基本操作
r.set('mykey', 'Hello')
value = r.get('mykey')
print(value)  # b'Hello'

常用场景 #

数据缓存 #

javascript
// 缓存数据库查询结果
async function getUser(userId) {
  const cacheKey = `user:${userId}`;
  
  // 先查缓存
  const cached = await client.get(cacheKey);
  if (cached) {
    return JSON.parse(cached);
  }
  
  // 查数据库
  const user = await db.query('SELECT * FROM users WHERE id = ?', [userId]);
  
  // 写入缓存,过期时间 1 小时
  await client.setEx(cacheKey, 3600, JSON.stringify(user));
  
  return user;
}

会话存储 #

javascript
// Express 使用 Redis 会话
const session = require('express-session');
const RedisStore = require('connect-redis').default;

app.use(session({
  store: new RedisStore({ client: redisClient }),
  secret: 'your-secret',
  resave: false,
  saveUninitialized: false,
  cookie: { secure: true, maxAge: 86400000 }
}));

分布式锁 #

javascript
// 使用 Redlock 实现分布式锁
const Redlock = require('redlock');

const redlock = new Redlock([redisClient]);

async function withLock(resource, ttl, callback) {
  let lock;
  try {
    lock = await redlock.acquire([resource], ttl);
    return await callback();
  } finally {
    if (lock) {
      await lock.release();
    }
  }
}

// 使用
await withLock('order:123', 5000, async () => {
  // 执行需要锁保护的操作
});

排行榜 #

javascript
// 使用 Sorted Set 实现排行榜
async function updateLeaderboard(userId, score) {
  await client.zAdd('leaderboard', { score, value: userId });
}

async function getTopUsers(count = 10) {
  return await client.zRangeWithScores('leaderboard', 0, count - 1, { REV: true });
}

async function getUserRank(userId) {
  return await client.zRevRank('leaderboard', userId);
}

消息队列 #

javascript
// 使用 List 实现消息队列
async function enqueue(queueName, message) {
  await client.lPush(queueName, JSON.stringify(message));
}

async function dequeue(queueName) {
  const result = await client.rPop(queueName);
  return result ? JSON.parse(result) : null;
}

// 阻塞式消费
async function consume(queueName, timeout = 0) {
  const result = await client.brPop(queueName, timeout);
  return result ? JSON.parse(result.element) : null;
}

高级功能 #

数据持久化 #

text
┌─────────────────────────────────────────────────────────────┐
│                    数据持久化选项                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  RDB 持久化                                                  │
│  ├── 定期快照                                               │
│  ├── 文件小                                                 │
│  ├── 可能丢失数据                                           │
│  └── 适合: 缓存场景                                         │
│                                                             │
│  AOF 持久化                                                  │
│  ├── 记录每个写操作                                         │
│  ├── 数据更完整                                             │
│  ├── 文件较大                                               │
│  └── 适合: 数据完整性要求高                                 │
│                                                             │
│  RDB + AOF                                                   │
│  ├── 结合两种方式                                           │
│  └── 最高可靠性                                             │
│                                                             │
└─────────────────────────────────────────────────────────────┘

配置持久化 #

bash
# 创建带持久化的高级缓存
az redis create \
  --resource-group myResourceGroup \
  --name myPersistentCache \
  --location eastus \
  --sku Premium \
  --vm-size p1 \
  --redis-configuration rdb-backup-enabled=true rdb-backup-frequency=15 rdb-backup-max-snapshot-count=1

集群配置 #

bash
# 创建集群缓存
az redis create \
  --resource-group myResourceGroup \
  --name myClusterCache \
  --location eastus \
  --sku Premium \
  --vm-size p1 \
  --shard-count 3

监控和诊断 #

监控指标 #

text
┌─────────────────────────────────────────────────────────────┐
│                    关键监控指标                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  性能指标                                                    │
│  ├── Cache Hit: 缓存命中率                                  │
│  ├── Connected Clients: 连接数                              │
│  ├── Operations Per Second: 每秒操作数                      │
│  └── Latency: 延迟                                          │
│                                                             │
│  内存指标                                                    │
│  ├── Used Memory: 已用内存                                  │
│  ├── Memory Fragmentation: 内存碎片率                       │
│  └── Evicted Keys: 驱逐键数                                 │
│                                                             │
│  负载指标                                                    │
│  ├── Server Load: 服务器负载                                │
│  ├── CPU Usage: CPU 使用率                                  │
│  └── Bandwidth: 带宽使用                                    │
│                                                             │
└─────────────────────────────────────────────────────────────┘

查看指标 #

bash
# 查看缓存指标
az monitor metrics list \
  --resource /subscriptions/.../redis/myCache \
  --metric "Cache Hits,Cache Misses,Used Memory" \
  --output table

最佳实践 #

性能优化 #

text
┌─────────────────────────────────────────────────────────────┐
│                    性能最佳实践                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. 选择合适的层级                                           │
│     └── 根据负载选择                                        │
│                                                             │
│  2. 使用连接池                                               │
│     └── 复用连接                                            │
│                                                             │
│  3. 合理设置过期时间                                         │
│     └── 避免内存溢出                                        │
│                                                             │
│  4. 使用管道                                                 │
│     └── 批量操作                                            │
│                                                             │
│  5. 避免大键                                                 │
│     └── 拆分大数据                                          │
│                                                             │
│  6. 监控驱逐策略                                             │
│     └── 配置合适的淘汰策略                                  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

安全建议 #

text
┌─────────────────────────────────────────────────────────────┐
│                    安全最佳实践                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. 使用 VNet 注入                                           │
│     └── 网络隔离                                            │
│                                                             │
│  2. 启用 TLS                                                 │
│     └── 加密传输                                            │
│                                                             │
│  3. 定期轮换密钥                                             │
│     └── 访问密钥管理                                        │
│                                                             │
│  4. 限制客户端连接                                           │
│     └── 配置最大连接数                                      │
│                                                             │
│  5. 使用防火墙规则                                           │
│     └── 限制访问 IP                                         │
│                                                             │
└─────────────────────────────────────────────────────────────┘

下一步 #

现在你已经掌握了 Redis 缓存的使用,接下来学习 网络服务 了解 Azure 网络解决方案!

最后更新:2026-03-29