- Published on
AWS ElastiCache Redis 連線指南
前置條件
- 已有 AWS 帳號和 ElastiCache 叢集
- 已建立 EC2 執行個體
- 已有 EC2 的 SSH 金鑰對
步驟一:設置 EC2 安全組
- 前往 AWS Console 的 EC2 Dashboard
- 選擇左側選單的「Security Groups」
- 找到 EC2 使用的安全組
- 編輯「Outbound rules」(出站規則)
- 新增規則:
- Type: Custom TCP
- Port Range: 6379
- Destination: ElastiCache 的安全組 ID
- Description: Redis Connection
步驟二:設置 ElastiCache 安全組
- 前往 ElastiCache Dashboard
- 選擇您的叢集
- 檢查安全組設定
- 編輯「Inbound rules」(入站規則)
- 新增規則:
- Type: Custom TCP
- Port Range: 6379
- Source: EC2 的安全組 ID
- Description: Allow EC2 Connection
步驟三:在 EC2 安裝必要工具
連接到您的 EC2:
ssh -i your-key.pem ubuntu@your-ec2-ip
安裝 Redis 工具:
# 更新套件資訊
sudo apt-get update
# 安裝 Redis 工具
sudo apt-get install redis-tools
步驟四:連接到 Redis
- 基本連接:
redis-cli -h YOUR-REDIS-ENDPOINT -p 6379
- 使用 TLS 連接:
redis-cli -h YOUR-REDIS-ENDPOINT -p 6379 --tls
針對您的環境:
redis-cli -h refactor-76uprq.serverless.apne1.cache.amazonaws.com -p 6379 --tls
故障排除
- 測試網路連通性:
# 測試 DNS 解析
ping YOUR-REDIS-ENDPOINT
# 測試端口連通性
nc -zv YOUR-REDIS-ENDPOINT 6379
- 確認安全組設定:
# 檢查當前 EC2 的安全組 ID
aws ec2 describe-instances --filters "Name=private-ip-address,Values=YOUR-EC2-PRIVATE-IP" --query "Reservations[].Instances[].SecurityGroups[].GroupId" --output text
- 連接失敗可能的原因:
- 安全組設定不正確
- VPC 設定不正確
- Redis AUTH 設定
- TLS 設定不正確
常用 Redis 命令
- 連接測試:
PING
- 基本操作:
SET key value # 設置值
GET key # 獲取值
DEL key # 刪除值
EXISTS key # 檢查鍵是否存在
EXPIRE key seconds # 設置過期時間
- 退出:
quit
安全建議
- 永遠使用安全組限制訪問
- 考慮啟用 Redis AUTH
- 在生產環境中使用 TLS 加密
- 定期更新 Redis 客戶端工具
- 避免在公網開放 Redis 端口
維護注意事項
- 定期檢查連接狀態
- 監控 Redis 記憶體使用情況
- 設置適當的警報機制
- 保持 Redis 工具的更新