Navigation

Celery + Redis で非同期タスク処理システム構築

📅 7月 8, 2025
👤
1 min read

Celery + Redis で非同期タスク処理システム構築

概要

Celery と Redis を組み合わせることで、Python アプリケーションで非同期タスク処理システムを構築することができます。Celery は分散タスクキューとして広く使用されており、Redis はそのバックエンドとして高速かつ信頼性の高いデータベースとして使用されます。この組み合わせは、非同期処理を効率的に行い、アプリケーションのパフォーマンスを向上させることができます。

解決する問題や課題

  • 非同期処理が必要なタスクを効率的に実行したい場合
  • ユーザーに対してリアルタイムな応答を返しつつ、バックグラウンドで長時間かかる処理を実行したい場合

前提知譆・必要ライブラリ

  • Python の基本知識
  • Django もしくは Flask などの Web フレームワークの基本知識
  • Celery
  • Redis

環境構築


# 必要ライブラリのインストール
pip install celery redis

実装コード


# タスクの定義と実行
from celery import Celery
import time

app = Celery('tasks', broker='redis://localhost:6379/0')

@app.task
def long_running_task():
    time.sleep(10)
    return 'Task completed'

# タスクの実行
result = long_running_task.delay()
print(result.get())

使用例


# 実際のユースケースを想定
# 非同期でメール送信などの処理を行う場合
@app.route('/send_email')
def send_email():
    send_email_task.delay()
    return 'Email sending task queued'

テストコード


# pytest を使ったテストコード例
import pytest
from myapp.tasks import long_running_task

def test_long_running_task():
    result = long_running_task.delay()
    assert result.get() == 'Task completed'

応用・カスタマイズ

  • タスクのエラーハンドリング
  • タスクのスケジューリング
  • タスクのチェーンやグループ化

関連技衙

  • Celery: https://docs.celeryproject.org/en/stable/
  • Redis: https://redis.io/
  • Celery 公式ドキュメント
  • Redis 公式ドキュメント

この記事では、Celery と Redis を使用して非同期タスク処理システムを構築する方法について紹介しました。これにより、長時間かかる処理を効率的に実行し、アプリケーションのパフォーマンスを向上させることができます。是非、実際のアプリケーション開発に活かしてみてください。

← Back to Python