RedisとPythonで始める
Min-jun Kim
Dev Intern · Leapcell

Key Takeaways
- Redisは高速なインメモリデータストアであり、キャッシングやリアルタイム処理に最適です。
- Pythonの
redis-py
ライブラリは、RedisをPythonアプリケーションに簡単に統合できます。 - Pythonを使用してRedisをインストールし、接続するには、最小限のセットアップが必要です。
Redisは、キャッシング、リアルタイム分析、メッセージブローキングに広く使用されている、高性能なインメモリキーバリューストアです。Pythonと組み合わせることで、スケーラブルで効率的なアプリケーションを構築するための強力なツールになります。このガイドでは、Redisを紹介し、redis-py
クライアントライブラリを通じてPythonで使用する方法を説明します。(Python Redis: A Beginner's Guide - DataCamp)
Redisとは?
Redis(Remote Dictionary Server)は、データベース、キャッシュ、メッセージブローカーとして使用できるオープンソースのインメモリデータ構造ストアです。文字列、ハッシュ、リスト、セット、ソートされたセットなど、さまざまなデータ構造をサポートしています。Redisはその速度と柔軟性で知られており、幅広いアプリケーションに適しています。(Python Redis: A Beginner's Guide - DataCamp)
PythonでRedisを使用する理由
Pythonのシンプルさと広範なエコシステムは、Redisとの統合に最適です。PythonでRedisを使用すると、開発者は次のことが可能になります。
- 効率的なキャッシングメカニズムを実装して、アプリケーションを高速化します。
- リアルタイムのデータ処理と分析を管理します。
- pub/subメッセージングや分散ロックなどの機能を備えたスケーラブルなシステムを構築します。(Python Redis: A Beginner's Guide - DataCamp)
Redisのセットアップ
Redisサーバーのインストール
まず、システムにRedisがインストールされている必要があります。オペレーティングシステムに応じて、さまざまな方法を使用してRedisをインストールできます。たとえば、Homebrewを使用したmacOSの場合:
brew install redis
Linuxシステムでは、パッケージマネージャーを使用できます。
sudo apt-get update sudo apt-get install redis-server
インストール後、Redisサーバーを起動します。(Python Redis: A Beginner's Guide - DataCamp)
redis-server
redis-py
ライブラリのインストール
redis-py
ライブラリは、Redisの公式Pythonクライアントです。pipを使用してインストールします。(ython redisRedis Simplified: A Concise Tutorial on Redis with Python, Beginner's Guide to Redis with Python - AskPython)
pip install redis
パフォーマンスを向上させるには、hiredisサポートを使用してインストールできます。(redis/redis-py: Redis Python client - GitHub)
pip install "redis[hiredis]"
PythonでRedisに接続する
Pythonを使用してRedisサーバーへの接続を確立する方法を次に示します。
import redis # Redisサーバーに接続 r = redis.Redis(host='localhost', port=6379, db=0)
値を設定および取得して、接続をテストできます。(Redis)
r.set('name', 'Alice') print(r.get('name')) # 出力: b'Alice'
応答を文字列に自動的にデコードするには:(redis/redis-py: Redis Python client - GitHub)
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True) r.set('name', 'Alice') print(r.get('name')) # 出力: Alice
Redisデータ構造の操作
文字列
文字列は、最も基本的なRedisデータ型です。(ython redisRedis Simplified: A Concise Tutorial on Redis with Python)
r.set('language', 'Python') print(r.get('language')) # 出力: Python
ハッシュ
ハッシュは、文字列フィールドと文字列値の間のマップであり、オブジェクトの表現に最適です。(Beginner's Guide to Redis with Python - AskPython)
r.hset('user:1000', 'name', 'Alice') r.hset('user:1000', 'email', 'alice@example.com') print(r.hgetall('user:1000')) # 出力: {'name': 'Alice', 'email': 'alice@example.com'}
リスト
リストは、文字列の順序付きコレクションです。(Beginner's Guide to Redis with Python - AskPython)
r.rpush('tasks', 'task1') r.rpush('tasks', 'task2') print(r.lrange('tasks', 0, -1)) # 出力: ['task1', 'task2']
セット
セットは、一意の文字列の順序なしコレクションです。
r.sadd('tags', 'python') r.sadd('tags', 'redis') print(r.smembers('tags')) # 出力: {'python', 'redis'}
ソートされたセット
ソートされたセットはセットに似ていますが、すべての文字列要素がスコアに関連付けられています。(Beginner's Guide to Redis with Python - AskPython)
r.zadd('leaderboard', {'Alice': 100, 'Bob': 95}) print(r.zrange('leaderboard', 0, -1, withscores=True)) # 出力: [('Bob', 95.0), ('Alice', 100.0)]
高度な機能
パイプライン
パイプラインを使用すると、複数のコマンドをバッチ処理して、クライアントとサーバー間のラウンドトリップ回数を減らすことができます。(Beginner's Guide to Redis with Python - AskPython)
pipe = r.pipeline() pipe.set('foo', 'bar') pipe.set('baz', 'qux') pipe.execute()
Pub/Sub
Redisは、パブリッシュ/サブスクライブメッセージングパラダイムをサポートしています。
pubsub = r.pubsub() pubsub.subscribe('channel1') # 別のスレッドまたはプロセスで r.publish('channel1', 'Hello, Redis!')
トランザクション
Redisトランザクションは、コマンドのグループがアトミックに実行されるようにします。(Beginner's Guide to Redis with Python - AskPython)
with r.pipeline() as pipe: while True: try: pipe.watch('balance') balance = int(pipe.get('balance')) if balance >= 50: pipe.multi() pipe.set('balance', balance - 50) pipe.execute() break else: pipe.unwatch() break except redis.WatchError: continue
ベストプラクティス
- 接続プールを使用する:Redis接続プールを使用して、複数の接続を効率的に管理します。
- 有効期限を設定する:キーの有効期限を使用して、古いデータを防ぎます。
- 例外を処理する:ネットワークの問題やコマンドエラーに対する適切なエラー処理を実装します。
- パフォーマンスを監視する:Redisのパフォーマンスメトリックを定期的に監視して、ボトルネックを特定します。(redis/redis-py: Redis Python client - GitHub, Beginner's Guide to Redis with Python - AskPython)
結論
RedisをPythonと統合すると、高性能アプリケーションを構築するための堅牢なソリューションが得られます。キャッシング、リアルタイム分析、メッセージングシステムのいずれを実装する場合でも、Redisはアプリケーションの効率とスケーラビリティを向上させるために必要なツールを提供します。(Beginner's Guide to Redis with Python - AskPython, Python Redis: A Beginner's Guide - DataCamp)
参考文献
- DataCamp: Python Redis: A Beginner's Guide
- Redis Official Documentation
- redis-py GitHub Repository
- AskPython: Beginner's Guide to Redis with Python
FAQs
Use a package manager like Homebrew (brew install redis
) or APT (sudo apt-get install redis-server
).
The official client is redis-py
, which you can install with pip install redis
.
It enables fast data access, caching, and real-time messaging with minimal overhead.
We are Leapcell, your top choice for hosting backend projects.
Leapcell is the Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis:
Multi-Language Support
- Develop with Node.js, Python, Go, or Rust.
Deploy unlimited projects for free
- pay only for usage — no requests, no charges.
Unbeatable Cost Efficiency
- Pay-as-you-go with no idle charges.
- Example: $25 supports 6.94M requests at a 60ms average response time.
Streamlined Developer Experience
- Intuitive UI for effortless setup.
- Fully automated CI/CD pipelines and GitOps integration.
- Real-time metrics and logging for actionable insights.
Effortless Scalability and High Performance
- Auto-scaling to handle high concurrency with ease.
- Zero operational overhead — just focus on building.
Explore more in the Documentation!
Follow us on X: @LeapcellHQ