feat(zram): 优化压缩算法检测逻辑并增加自动回退机制

This commit is contained in:
严浩
2026-03-23 10:51:08 +08:00
parent 7e84740222
commit 85d0825a88
+38 -7
View File
@@ -300,7 +300,7 @@ install_zram() {
return 0
fi
local total_mem algo percent
local total_mem algo percent available_algorithms
total_mem=$(awk '/MemTotal/{print int($2 / 1024)}' /proc/meminfo)
if ! [[ "$total_mem" =~ ^[0-9]+$ ]] || [ "$total_mem" -le 0 ]; then
@@ -308,22 +308,48 @@ install_zram() {
return 0
fi
available_algorithms=$(tr ' ' '\n' </sys/block/zram0/comp_algorithm 2>/dev/null | tr -d '[]' || true)
echo "检测到支持的 zram 算法: ${available_algorithms:-unknown}"
choose_zram_algorithm() {
local candidate
for candidate in "$@"; do
if printf '%s\n' "$available_algorithms" | grep -qx "$candidate"; then
printf '%s\n' "$candidate"
return 0
fi
done
return 1
}
echo "检测到总内存: ${total_mem}MB"
if [ "$total_mem" -le 2500 ]; then
percent="100"
if [ -r /sys/block/zram0/comp_algorithm ] && grep -qw zstd /sys/block/zram0/comp_algorithm; then
algo="zstd"
if algo=$(choose_zram_algorithm zstd lz4 lzo-rle lzo); then
if [ "$algo" = "zstd" ]; then
echo "策略:内存 <= 2G,使用 zstd 算法 (100% 占比)"
else
algo="lz4"
echo "策略:内存 <= 2G,但内核未报告 zstd 支持,回退到 lz4 (100% 占比)"
echo "策略:内存 <= 2G,但内核未报告 zstd 支持,回退到 $algo (100% 占比)"
fi
else
print_yellow "未检测到受支持的 zram 压缩算法,跳过 zram 配置"
return 0
fi
else
algo="lz4"
percent="60"
if algo=$(choose_zram_algorithm lz4 zstd lzo-rle lzo); then
if [ "$algo" = "lz4" ]; then
echo "策略:内存 > 2G,使用 lz4 算法 (60% 占比)"
else
echo "策略:内存 > 2G,但内核未报告 lz4 支持,回退到 $algo (60% 占比)"
fi
else
print_yellow "未检测到受支持的 zram 压缩算法,跳过 zram 配置"
return 0
fi
fi
cat <<EOF >/etc/default/zramswap
@@ -333,7 +359,12 @@ PERCENT=$percent
PRIORITY=100
EOF
systemctl restart zramswap
if ! systemctl restart zramswap; then
print_red "zramswap 服务重启失败"
systemctl status zramswap.service --no-pager || true
journalctl -u zramswap.service -n 20 --no-pager || true
return 1
fi
echo "---------------------------------------"
echo "zram 部署完成!当前状态:"