Skip to content

Commit

Permalink
feature:增加redis
Browse files Browse the repository at this point in the history
  • Loading branch information
xieyumc committed Sep 25, 2024
1 parent 90ad887 commit dc9b883
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 11 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/postgres_data/
/postgres_data/*
46 changes: 37 additions & 9 deletions Django/blog/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,64 @@
from .models import Post, Image
from .serializers import PostSerializer, ImageSerializer
import mimetypes
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.core.cache import cache # 引入缓存
from django.conf import settings # 访问缓存超时配置
import hashlib # 用于生成唯一缓存键


# 用于处理文章的常规CRUD操作
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer

def get_queryset(self):
return Post.objects.filter(available=True)
# 检查缓存中是否有文章数据
cached_queryset = cache.get('post_queryset')
if cached_queryset:
return cached_queryset

# 如果缓存中没有数据,则查询数据库并缓存
queryset = Post.objects.filter(available=True)
cache.set('post_queryset', queryset, timeout=60 * 15) # 缓存15分钟
return queryset


# 用于提供文章图片的视图函数
class ImageViewSet(viewsets.ModelViewSet):
queryset = Image.objects.all()
serializer_class = ImageSerializer


def post_image(request, post_id, image_index):
post = get_object_or_404(Post, id=post_id)
images = post.images.all().order_by('id') # 按ID排序,确保顺序一致
image_index -= 1 # 使索引从1开始计数

if images and 0 <= image_index < len(images):
image = images[image_index]

# 生成唯一的缓存键,基于文章ID和图片索引
cache_key = f'post_{post_id}_image_{image_index}'
cached_image = cache.get(cache_key)

if cached_image:
# 从缓存中返回图片数据
mime_type, _ = mimetypes.guess_type(image.image.path)
if not mime_type:
mime_type = "application/octet-stream"
response = HttpResponse(cached_image, content_type=mime_type)
response['Cache-Control'] = 'public, max-age=2592000'
return response

# 如果缓存中没有图片数据,则读取文件并缓存
image_path = image.image.path
# 自动检测文件的 MIME 类型
mime_type, _ = mimetypes.guess_type(image_path)
if not mime_type:
mime_type = "application/octet-stream" # 当类型无法识别时使用默认类型
with open(image_path, 'rb') as f:
response = HttpResponse(f.read(), content_type=mime_type)
# 设置缓存头,缓存30天
image_data = f.read()
cache.set(cache_key, image_data, timeout=2592000) # 缓存30天
mime_type, _ = mimetypes.guess_type(image_path)
if not mime_type:
mime_type = "application/octet-stream"
response = HttpResponse(image_data, content_type=mime_type)
response['Cache-Control'] = 'public, max-age=2592000'
return response
else:
Expand Down
23 changes: 23 additions & 0 deletions Django/djangoProject/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from pathlib import Path
import os
import redis



Expand Down Expand Up @@ -110,6 +111,28 @@

}

# Redis 相关设置,从环境变量中读取配置,并设置默认值
REDIS_HOST = os.environ.get('REDIS_HOST', 'localhost') # 默认是本地
REDIS_PORT = os.environ.get('REDIS_PORT', 6379) # 默认端口为6379
REDIS_DB = os.environ.get('REDIS_DB', 0) # 默认 Redis 数据库为 0
REDIS_URL = f'redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}'

# CACHES 配置,将 Redis 用作缓存后端
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': REDIS_URL,
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
}
}
}

# 将会话存储到 Redis 中
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'



# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
Expand Down
4 changes: 3 additions & 1 deletion Django/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,6 @@ sqlparse==0.5.0
djangorestframework
gunicorn
Pillow
psycopg2-binary
psycopg2-binary
django-redis
redis
9 changes: 9 additions & 0 deletions GitHub Action Build Docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@ services:
- POSTGRES_PASSWORD=pYrdip-kevset-mihby2
- POSTGRES_HOST=db
- POSTGRES_PORT=5432
- REDIS_HOST=redis # 使用 Redis 容器名称作为主机名
- REDIS_PORT=6379 # Redis 端口号(内部通信)
depends_on:
- db
- redis # 新增 Redis 依赖
volumes:
- ./media/post_images:/app/media/post_images

Expand Down Expand Up @@ -45,6 +48,12 @@ services:
networks:
- appleblog_network

redis:
image: redis:latest # 使用官方 Redis 镜像
container_name: redis
networks:
- appleblog_network # 不暴露端口,只在网络内部通信

networks:
appleblog_network:
driver: bridge
Expand Down
10 changes: 9 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@ services:
- POSTGRES_PASSWORD=pYrdip-kevset-mihby2
- POSTGRES_HOST=db
- POSTGRES_PORT=5432
- REDIS_HOST=redis # Redis 容器名称
- REDIS_PORT=6379 # Redis 内部端口
depends_on:
- db
- redis # 添加对 redis 的依赖
volumes:
- ./media/post_images:/app/media/post_images

Expand All @@ -40,12 +43,17 @@ services:
- POSTGRES_DB=postgres
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=pYrdip-kevset-mihby2

volumes:
- ./postgres_data:/var/lib/postgresql/data
networks:
- appleblog_network

redis:
image: redis:latest # 使用官方 Redis 镜像
container_name: redis
networks:
- appleblog_network

watchtower:
image: containrrr/watchtower
container_name: watchtower
Expand Down

0 comments on commit dc9b883

Please sign in to comment.