Redis完全ガイド
Redis完全ガイド
Section titled “Redis完全ガイド”Redisの実践的な使い方を、実務で使える実装例とベストプラクティスとともに詳しく解説します。
1. Redisとは
Section titled “1. Redisとは”Redisの特徴
Section titled “Redisの特徴”Redis(Remote Dictionary Server)は、インメモリデータストアです。高速な読み書きが可能で、キャッシュ、セッション管理、メッセージキューなどに使用されます。
Redisの特徴 ├─ インメモリデータストア(高速) ├─ 豊富なデータ型(String、List、Set、Hash、Sorted Setなど) ├─ 永続化オプション(RDB、AOF) ├─ レプリケーション対応 └─ クラスタリング対応なぜRedisを選ぶのか
Section titled “なぜRedisを選ぶのか”Redisを選ぶべき場合:
- 高速なキャッシュが必要
- セッション管理が必要
- リアルタイムデータ処理が必要
- メッセージキューが必要
Redisを選ばないべき場合:
- 大容量データの永続保存が必要(データベースの方が適している)
- 複雑なクエリが必要(データベースの方が適している)
2. Redisのインストールとセットアップ
Section titled “2. Redisのインストールとセットアップ”macOSでのインストール
Section titled “macOSでのインストール”# Homebrewを使用brew install redis
# サービスを開始brew services start redis
# Redisに接続redis-cliLinuxでのインストール
Section titled “Linuxでのインストール”# Ubuntu/Debiansudo apt-get updatesudo apt-get install redis-server
# サービスを開始sudo systemctl start redis-serversudo systemctl enable redis-server
# Redisに接続redis-cliWindowsでのインストール
Section titled “Windowsでのインストール”- Redis公式サイトからインストーラーをダウンロード
- インストーラーを実行し、指示に従ってインストール
- Redis CLIまたはRedis Desktop Managerから接続
# Redis設定ファイルの編集(redis.conf)# パスワードの設定requirepass mypassword
# 永続化の設定save 900 1save 300 10save 60 10000
# メモリ制限の設定maxmemory 256mbmaxmemory-policy allkeys-lru3. データ型と基本操作
Section titled “3. データ型と基本操作”String(文字列)
Section titled “String(文字列)”# 値の設定SET user:1:name "Alice"SET user:1:email "alice@example.com"
# 値の取得GET user:1:name
# 値の存在確認EXISTS user:1:name
# 値の削除DEL user:1:name
# 値のインクリメントINCR user:1:viewsINCRBY user:1:views 10
# 値のデクリメントDECR user:1:viewsDECRBY user:1:views 5
# 有効期限の設定SET user:1:session "session_token" EX 3600TTL user:1:sessionHash(ハッシュ)
Section titled “Hash(ハッシュ)”# ハッシュの設定HSET user:1 name "Alice" email "alice@example.com" age 30
# ハッシュの取得HGET user:1 nameHGETALL user:1
# ハッシュの更新HSET user:1 age 31
# ハッシュの削除HDEL user:1 email
# ハッシュの存在確認HEXISTS user:1 name
# ハッシュのすべてのキーを取得HKEYS user:1
# ハッシュのすべての値を取得HVALS user:1List(リスト)
Section titled “List(リスト)”# リストの先頭に追加LPUSH tasks "task1" "task2" "task3"
# リストの末尾に追加RPUSH tasks "task4" "task5"
# リストの取得LRANGE tasks 0 -1
# リストの先頭から取得(削除)LPOP tasks
# リストの末尾から取得(削除)RPOP tasks
# リストの長さを取得LLEN tasks
# リストの特定の位置の値を取得LINDEX tasks 0
# リストの特定の位置の値を設定LSET tasks 0 "new_task"Set(集合)
Section titled “Set(集合)”# セットへの追加SADD tags "redis" "database" "cache"
# セットの取得SMEMBERS tags
# セットの要素数の取得SCARD tags
# セットの要素の存在確認SISMEMBER tags "redis"
# セットからの削除SREM tags "cache"
# セットの和集合SUNION tags1 tags2
# セットの積集合SINTER tags1 tags2
# セットの差集合SDIFF tags1 tags2Sorted Set(順序付き集合)
Section titled “Sorted Set(順序付き集合)”# ソート済みセットへの追加ZADD leaderboard 100 "Alice" 200 "Bob" 150 "Charlie"
# ソート済みセットの取得(昇順)ZRANGE leaderboard 0 -1 WITHSCORES
# ソート済みセットの取得(降順)ZREVRANGE leaderboard 0 -1 WITHSCORES
# スコアの取得ZSCORE leaderboard "Alice"
# ランクの取得ZRANK leaderboard "Alice"ZREVRANK leaderboard "Alice"
# スコア範囲での取得ZRANGEBYSCORE leaderboard 100 200
# スコアの更新ZINCRBY leaderboard 50 "Alice"4. 高度な機能
Section titled “4. 高度な機能”Pub/Sub(パブリッシュ/サブスクライブ)
Section titled “Pub/Sub(パブリッシュ/サブスクライブ)”# チャンネルの購読SUBSCRIBE notifications
# チャンネルへのメッセージ送信(別のクライアントから)PUBLISH notifications "New message"
# パターンマッチングでの購読PSUBSCRIBE notifications:*
# チャンネルの購読解除UNSUBSCRIBE notificationsトランザクション
Section titled “トランザクション”# トランザクションの開始MULTI
# コマンドの追加SET key1 "value1"SET key2 "value2"INCR counter
# トランザクションの実行EXEC
# トランザクションのキャンセルDISCARDパイプライン
Section titled “パイプライン”# パイプラインの使用(複数のコマンドを一度に送信)# クライアントライブラリで実装# Pythonの例:import redisr = redis.Redis()pipe = r.pipeline()pipe.set('key1', 'value1')pipe.set('key2', 'value2')pipe.execute()5. 永続化
Section titled “5. 永続化”RDB(Redis Database)
Section titled “RDB(Redis Database)”# redis.confの設定save 900 1 # 900秒以内に1回以上の変更があれば保存save 300 10 # 300秒以内に10回以上の変更があれば保存save 60 10000 # 60秒以内に10000回以上の変更があれば保存
# 手動でのRDB保存BGSAVE
# 同期的なRDB保存(ブロッキング)SAVEAOF(Append Only File)
Section titled “AOF(Append Only File)”# redis.confの設定appendonly yesappendfsync everysec # always, everysec, no
# AOFファイルの書き換えBGREWRITEAOFRDB vs AOF
Section titled “RDB vs AOF”| 特徴 | RDB | AOF |
|---|---|---|
| データ損失 | 最後の保存時点まで | 最小限 |
| パフォーマンス | 高速 | やや低速 |
| ファイルサイズ | 小さい | 大きい |
| リカバリ速度 | 高速 | やや低速 |
6. レプリケーション
Section titled “6. レプリケーション”マスター・スレーブレプリケーション
Section titled “マスター・スレーブレプリケーション”# スレーブサーバーの設定(redis.conf)replicaof 192.168.1.100 6379masterauth mypassword
# レプリケーションの状態確認INFO replication
# レプリケーションの開始REPLICAOF 192.168.1.100 6379
# レプリケーションの停止REPLICAOF NO ONEセンチネル(Sentinel)
Section titled “センチネル(Sentinel)”# sentinel.confの設定sentinel monitor mymaster 192.168.1.100 6379 2sentinel auth-pass mymaster mypasswordsentinel down-after-milliseconds mymaster 5000sentinel failover-timeout mymaster 10000
# センチネルの起動redis-sentinel sentinel.conf7. クラスタリング
Section titled “7. クラスタリング”Redis Clusterの設定
Section titled “Redis Clusterの設定”# 各ノードの設定(redis.conf)cluster-enabled yescluster-config-file nodes.confcluster-node-timeout 5000
# クラスタの作成redis-cli --cluster create \ 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 \ 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005 \ --cluster-replicas 1
# クラスタの状態確認redis-cli -c -p 7000 CLUSTER NODESクラスタの操作
Section titled “クラスタの操作”# クラスタモードでの接続redis-cli -c -p 7000
# クラスタの情報取得CLUSTER INFO
# スロットの確認CLUSTER SLOTS8. パフォーマンス最適化
Section titled “8. パフォーマンス最適化”メモリ最適化
Section titled “メモリ最適化”# メモリ使用量の確認INFO memory
# メモリ制限の設定maxmemory 256mbmaxmemory-policy allkeys-lru # allkeys-lru, volatile-lru, allkeys-random, volatile-random, volatile-ttl, noeviction
# メモリ使用量の削減MEMORY DOCTOR# 最大接続数の設定(redis.conf)maxclients 10000
# 接続数の確認INFO clientsパイプラインとバッチ処理
Section titled “パイプラインとバッチ処理”# Pythonの例import redisr = redis.Redis()
# パイプラインの使用pipe = r.pipeline()for i in range(1000): pipe.set(f'key{i}', f'value{i}')pipe.execute()9. セキュリティ
Section titled “9. セキュリティ”# パスワードの設定(redis.conf)requirepass mypassword
# 認証の実行AUTH mypassword
# 認証付きでの接続redis-cli -a mypasswordACL(Access Control List)
Section titled “ACL(Access Control List)”# ユーザーの作成ACL SETUSER alice on >password123 ~cached:* +get +set
# ユーザーの確認ACL LIST
# ユーザーでの接続redis-cli --user alice --pass password123TLS/SSL
Section titled “TLS/SSL”# TLSの設定(redis.conf)tls-port 6380tls-cert-file /path/to/cert.pemtls-key-file /path/to/key.pemtls-ca-cert-file /path/to/ca.pem
# TLS接続redis-cli --tls --cert /path/to/cert.pem --key /path/to/key.pem10. 実践的な使用例
Section titled “10. 実践的な使用例”# Pythonの例import redisimport json
r = redis.Redis(host='localhost', port=6379, db=0)
def get_user(user_id): cache_key = f'user:{user_id}' cached_user = r.get(cache_key)
if cached_user: return json.loads(cached_user)
# データベースから取得 user = db.get_user(user_id)
# キャッシュに保存(1時間) r.setex(cache_key, 3600, json.dumps(user))
return userセッション管理
Section titled “セッション管理”# Pythonの例import redisimport uuid
r = redis.Redis(host='localhost', port=6379, db=0)
def create_session(user_id): session_id = str(uuid.uuid4()) session_key = f'session:{session_id}'
r.setex(session_key, 3600, user_id) # 1時間
return session_id
def get_session(session_id): session_key = f'session:{session_id}' user_id = r.get(session_key)
if user_id: r.expire(session_key, 3600) # 有効期限を延長
return user_id# Pythonの例import redisimport time
r = redis.Redis(host='localhost', port=6379, db=0)
def rate_limit(user_id, limit=100, window=3600): key = f'rate_limit:{user_id}' current = r.incr(key)
if current == 1: r.expire(key, window)
if current > limit: return False
return Trueリアルタイムランキング
Section titled “リアルタイムランキング”# Pythonの例import redis
r = redis.Redis(host='localhost', port=6379, db=0)
def update_score(user_id, score): r.zadd('leaderboard', {user_id: score})
def get_top_users(limit=10): return r.zrevrange('leaderboard', 0, limit-1, withscores=True)11. 監視とログ
Section titled “11. 監視とログ”# サーバー情報の取得INFO
# 特定のセクションの情報取得INFO memoryINFO statsINFO replication
# クライアント情報の取得CLIENT LIST
# スロークエリの確認SLOWLOG GET 10メトリクスの監視
Section titled “メトリクスの監視”# メモリ使用量INFO memory | grep used_memory_human
# 接続数INFO clients | grep connected_clients
# コマンド統計INFO stats | grep total_commands_processed12. よくある問題と解決方法
Section titled “12. よくある問題と解決方法”問題1: メモリ不足
Section titled “問題1: メモリ不足”# メモリ使用量の確認INFO memory
# メモリ制限の設定CONFIG SET maxmemory 256mbCONFIG SET maxmemory-policy allkeys-lru
# 大きなキーの確認redis-cli --bigkeys問題2: パフォーマンスの低下
Section titled “問題2: パフォーマンスの低下”# スロークエリの確認SLOWLOG GET 10
# スロークエリの設定CONFIG SET slowlog-log-slower-than 10000
# メモリフラグメンテーションの確認MEMORY STATS問題3: レプリケーションの遅延
Section titled “問題3: レプリケーションの遅延”# レプリケーションの状態確認INFO replication
# レプリケーションの遅延確認redis-cli --latency -h replica_host -p 6379Redis完全ガイドのポイント:
- データ型: String、Hash、List、Set、Sorted Set
- 高度な機能: Pub/Sub、トランザクション、パイプライン
- 永続化: RDB、AOF
- レプリケーション: マスター・スレーブ、センチネル
- クラスタリング: 水平スケーリング
- パフォーマンス最適化: メモリ最適化、接続プール
- セキュリティ: 認証、ACL、TLS/SSL
- 実践例: キャッシュ、セッション管理、レート制限
適切なRedisの使用により、高速でスケーラブルなアプリケーションを構築できます。