数据库层面
- 数据库查询优化
- 使用select_related和prefetch_related:在查询时,若涉及外键关联,
select_related
用于JOIN
操作,减少数据库查询次数。例如,在商品详情页中,商品模型关联了分类模型,查询商品时可使用Product.objects.select_related('category').get(id=product_id)
。prefetch_related
适用于多对多或一对多关系,它会分别执行查询,然后在Python中合并结果,如Product.objects.prefetch_related('tags').all()
。
- 避免N + 1查询:在循环中查询数据库会导致N + 1问题,应尽量一次性获取所需数据。如获取多个商品的评论,应使用
Comment.objects.filter(product__in=products).all()
,而不是在遍历商品时逐个查询评论。
- 数据库索引优化
- 合理添加索引:在经常用于查询条件、排序或连接的字段上添加索引。在Django模型中,可在字段定义时使用
db_index=True
,如class Product(models.Model): name = models.CharField(max_length=100, db_index=True)
。对于复合索引,可在模型的Meta
类中定义indexes = [models.Index(fields=['field1', 'field2'])]
。
- 读写分离
- 配置数据库路由:在Django项目的
settings.py
中配置数据库路由。首先定义一个数据库路由类,如:
class ReadWriteRouter:
def db_for_read(self, model, **hints):
return 'read_db'
def db_for_write(self, model, **hints):
return 'write_db'
def allow_relation(self, obj1, obj2, **hints):
db_list = ('read_db', 'write_db')
if obj1._state.db in db_list and obj2._state.db in db_list:
return True
return None
- 然后在`settings.py`中设置`DATABASE_ROUTERS = ['path.to.ReadWriteRouter']`,并配置好`read_db`和`write_db`的数据库连接信息。
缓存层面
- 页面缓存
- 使用中间件:在
settings.py
中配置页面缓存中间件django.middleware.cache.UpdateCacheMiddleware
和django.middleware.cache.FetchFromCacheMiddleware
。设置缓存时间,如CACHE_MIDDLEWARE_SECONDS = 60 * 15
(15分钟)。对于特定视图,可在视图函数上使用@cache_page
装饰器,如from django.views.decorators.cache import cache_page; @cache_page(60 * 5) def product_list(request): pass
。
- 视图缓存
- 使用@cache_page装饰器:除了在视图函数上使用,也可在类视图中使用。例如:
from django.views.generic import ListView
from django.views.decorators.cache import cache_page
from django.utils.decorators import method_decorator
@method_decorator(cache_page(60 * 10), name='dispatch')
class ProductListView(ListView):
model = Product
- 对象缓存
- 手动缓存对象:使用
django.core.cache
模块。例如,获取商品对象时,先尝试从缓存中获取,若不存在则查询数据库并缓存。
from django.core.cache import cache
def get_product(product_id):
product = cache.get(f'product_{product_id}')
if not product:
product = Product.objects.get(id=product_id)
cache.set(f'product_{product_id}', product, 60 * 60)
return product
服务器配置方面
- 使用Gunicorn + Nginx
- 安装和配置Gunicorn:使用
pip install gunicorn
安装,然后创建一个Gunicorn启动配置文件,如gunicorn.conf.py
,配置工作进程数等参数,如workers = multiprocessing.cpu_count() * 2 + 1
。使用gunicorn -c gunicorn.conf.py project_name.wsgi
启动应用。
- 配置Nginx作为反向代理:在Nginx配置文件中,设置反向代理到Gunicorn,如:
server {
listen 80;
server_name your_domain.com;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X - Real - IP $remote_addr;
proxy_set_header X - Forwarded - For $proxy_add_x_forwarded_for;
proxy_set_header X - Forwarded - Proto $scheme;
}
}
- 启用HTTPS
- 获取SSL证书:可通过Let's Encrypt等免费证书颁发机构获取。
- 配置Nginx支持HTTPS:在Nginx配置文件中添加SSL相关配置,如:
server {
listen 443 ssl;
server_name your_domain.com;
ssl_certificate /path/to/your_cert.pem;
ssl_certificate_key /path/to/your_key.pem;
location / {
proxy_pass http://127.0.0.1:8000;
# 其他代理配置
}
}
- 优化服务器资源配置
- 调整系统参数:如增加文件描述符限制,在
/etc/security/limits.conf
中添加* soft nofile 65535
和* hard nofile 65535
。调整内核参数,如net.ipv4.tcp_tw_reuse = 1
和net.ipv4.tcp_fin_timeout = 30
等,在/etc/sysctl.conf
中配置并执行sysctl -p
生效。