一、APT包缓存配置(针对软件包下载优化)
APT缓存用于存储已下载的软件包,避免重复下载,提升多客户端或多任务场景下的软件安装效率。
/etc/apt/apt.conf.d/95local,添加以下内容:Acquire::http::Cache-Control "max-age=600, max-size=500M"; # 缓存有效期10分钟,最大500MB
Acquire::http::Cache::Expire "7d"; # 缓存过期时间为7天
保存后重启APT服务使配置生效:sudo systemctl restart apt-daily.service apt-daily-upgrade.service。/mnt/cache/apt),可添加以下配置:Dir::Cache::Archives "/mnt/cache/apt";
sudo apt clean # 清理所有已下载的软件包
sudo apt autoclean # 仅清理过期的软件包
二、Squid代理缓存配置(通用HTTP/HTTPS缓存)
Squid是一款功能强大的代理缓存服务器,可缓存网页、软件包等资源,适用于局域网内多设备共享缓存,减少带宽消耗。
sudo apt update && sudo apt install squid
/etc/squid/squid.conf,修改以下关键项:
3128,可根据需求调整:http_port 3128
/var/spool/squid目录,100GB存储空间,16级子目录,每级256个子目录):cache_dir ufs /var/spool/squid 100 16 256
192.168.1.0/24)访问缓存服务:acl localnet src 192.168.1.0/24
http_access allow localnet
sudo systemctl start squid
sudo systemctl enable squid
192.168.1.100:3128)。三、内存缓存配置(Memcached/Redis,提升应用性能)
内存缓存(如Memcached、Redis)用于存储频繁访问的数据(如数据库查询结果、会话信息),减少数据库负载,提升Web应用响应速度。
sudo apt install memcached/etc/memcached.conf,修改-m参数(单位:MB,示例为512MB):-m 512
sudo systemctl start memcached && sudo systemctl enable memcachedsudo apt install php-memcached
在PHP代码中连接Memcached:$memcached = new Memcached();
$memcached->addServer('localhost', 11211);
$data = $memcached->get('cache_key');
if (!$data) {
$data = fetch_from_database(); // 从数据库获取数据
$memcached->set('cache_key', $data, 3600); // 缓存1小时
}
sudo apt install redis-server/etc/redis/redis.conf,启用RDB或AOF持久化(如save 60 1000表示60秒内至少1000次修改则保存):save 60 1000
sudo systemctl start redis-server && sudo systemctl enable redis-serversudo apt install php-redis
在PHP代码中连接Redis:$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$data = $redis->get('cache_key');
if (!$data) {
$data = fetch_from_database();
$redis->setex('cache_key', 3600, $data); // 缓存1小时
}
四、Web服务器缓存配置(Nginx/Varnish,加速静态/动态内容)
Web服务器缓存用于缓存静态文件(如图片、CSS、JS)或动态内容,减少后端服务器压力,提升页面加载速度。
/etc/nginx/sites-available/default),添加以下内容:proxy_cache_path /usr/nginx/cache/webpages levels=1:2 keys_zone=webpages:30m max_size=2g inactive=60m use_temp_path=off;
其中/usr/nginx/cache/webpages为缓存目录,webpages为缓存区域名称,30m为内存中缓存键的大小,2g为磁盘缓存最大大小,60m为内容不活动60分钟后过期。server块中添加以下内容,缓存后端返回的200状态码内容10分钟:location / {
proxy_pass http://backend_server; # 替换为实际后端服务器地址
proxy_cache webpages;
proxy_cache_valid 200 10m;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
sudo systemctl restart nginxsudo apt install varnish/etc/varnish/default.vcl,设置后端服务器(如Nginx运行在127.0.0.1:8080)和缓存策略:backend default {
.host = "127.0.0.1";
.port = "8080";
}
sub vcl_recv {
if (req.method == "PURGE") {
return (purge); # 支持PURGE请求清除缓存
}
}
sub vcl_backend_response {
if (beresp.http.Cache-Control ~ "no-cache") {
return (pass); # 不缓存no-cache的内容
}
set beresp.ttl = 1h; # 设置缓存有效期1小时
}
sudo systemctl start varnish && sudo systemctl enable varnish80端口,若与Nginx冲突,需调整端口或使用Nginx作为反向代理。