anpanman
Published on

AWS ElastiCache Redis 連線指南

前置條件

  • 已有 AWS 帳號和 ElastiCache 叢集
  • 已建立 EC2 執行個體
  • 已有 EC2 的 SSH 金鑰對

步驟一:設置 EC2 安全組

  1. 前往 AWS Console 的 EC2 Dashboard
  2. 選擇左側選單的「Security Groups」
  3. 找到 EC2 使用的安全組
  4. 編輯「Outbound rules」(出站規則)
  5. 新增規則:
    • Type: Custom TCP
    • Port Range: 6379
    • Destination: ElastiCache 的安全組 ID
    • Description: Redis Connection

步驟二:設置 ElastiCache 安全組

  1. 前往 ElastiCache Dashboard
  2. 選擇您的叢集
  3. 檢查安全組設定
  4. 編輯「Inbound rules」(入站規則)
  5. 新增規則:
    • 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

  1. 基本連接:
redis-cli -h YOUR-REDIS-ENDPOINT -p 6379
  1. 使用 TLS 連接:
redis-cli -h YOUR-REDIS-ENDPOINT -p 6379 --tls

針對您的環境:

redis-cli -h refactor-76uprq.serverless.apne1.cache.amazonaws.com -p 6379 --tls

故障排除

  1. 測試網路連通性:
# 測試 DNS 解析
ping YOUR-REDIS-ENDPOINT

# 測試端口連通性
nc -zv YOUR-REDIS-ENDPOINT 6379
  1. 確認安全組設定:
# 檢查當前 EC2 的安全組 ID
aws ec2 describe-instances --filters "Name=private-ip-address,Values=YOUR-EC2-PRIVATE-IP" --query "Reservations[].Instances[].SecurityGroups[].GroupId" --output text
  1. 連接失敗可能的原因:
    • 安全組設定不正確
    • VPC 設定不正確
    • Redis AUTH 設定
    • TLS 設定不正確

常用 Redis 命令

  1. 連接測試:
PING
  1. 基本操作:
SET key value        # 設置值
GET key              # 獲取值
DEL key             # 刪除值
EXISTS key          # 檢查鍵是否存在
EXPIRE key seconds  # 設置過期時間
  1. 退出:
quit

安全建議

  1. 永遠使用安全組限制訪問
  2. 考慮啟用 Redis AUTH
  3. 在生產環境中使用 TLS 加密
  4. 定期更新 Redis 客戶端工具
  5. 避免在公網開放 Redis 端口

維護注意事項

  1. 定期檢查連接狀態
  2. 監控 Redis 記憶體使用情況
  3. 設置適當的警報機制
  4. 保持 Redis 工具的更新

參考資源