通过缓存可以显著减少服务器的负载,提高网站的响应速度和用户体验。以下是一些常见的缓存策略:
Cache-Control、Expires等HTTP头信息,告诉浏览器哪些资源可以被缓存以及缓存的时间。Cache-Control: max-age=3600
Expires: Wed, 21 Oct 2025 07:28:00 GMT
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
data = r.get('key')
if data is None:
data = fetch_data_from_db()
r.set('key', data, ex=3600) # 缓存1小时
location /static/ {
expires 1h;
add_header Cache-Control "public";
}
<?php echo $cache->get('header'); ?>
SET GLOBAL query_cache_size = 1000000;
SET GLOBAL query_cache_type = 1;
@Cacheable(value = "users", key = "#id")
public User getUserById(int id) {
return userRepository.findById(id);
}
通过综合运用上述策略,可以有效地减少服务器负载,提升系统的整体性能和稳定性。