在Django中使用Celery进行缓存清理

2023-04-11 00:00:00 django 缓存 清理

首先需要安装Celery和Django-Celery:

pip install celery django-celery

然后在Django的settings.py中添加以下配置:

# celery配置
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = TIME_ZONE

# django-celery配置
INSTALLED_APPS += ['django_celery']
CELERYBEAT_SCHEDULER = 'django_celery_beat.schedulers.DatabaseScheduler'

接下来在Django的app中创建一个tasks.py文件,定义要执行的任务:

from celery import shared_task
from django.core.cache import cache


@shared_task
def clear_cache():
    cache.clear()
    return 'Cache cleared'

然后在app中的views.py文件中调用该任务:

from .tasks import clear_cache
from django.http import HttpResponse


def clear_cache_view(request):
    clear_cache.delay()
    return HttpResponse('Cache clearing task has been added to the Celery queue!')

最后需要启动Celery worker和beat:

celery -A your_project_name worker -l info
celery -A your_project_name beat -l info

现在每次调用clear_cache_view视图函数时,清除缓存任务将被添加到Celery队列中,并在后台执行。

相关文章