当磁盘小文件数量增加时,机械硬盘的 4K 读写速度 容易成为性能瓶颈。由于固态硬盘(SSD)价格较高,全盘替换成本较大,因此可以采用 SSD 作为缓存盘、机械硬盘作为数据盘 的方案来提升 I/O 性能。本文介绍如何使用 bcache 在 Linux (Debian) 系统中配置 SSD 缓存加速。
bcache 简介
bcache (block cache) 是 Linux 内核块层的缓存机制,用于提升传统机械硬盘(HDD)的读写性能。它的特点包括:文章源自堕落的鱼-https://www.duoluodeyu.com/2791.html
- 支持多个缓存设备:可以使用多个 SSD 设备作为缓存,提高灵活性。
- 支持多种缓存模式:可配置回写、写通、直写等策略,满足不同应用需求。
- 稳定可靠:支持非正常关机恢复,适用于生产环境。
1. 开启 bcache 内核模块
使用以下命令加载 bcache 模块,并检查是否成功:文章源自堕落的鱼-https://www.duoluodeyu.com/2791.html
modprobe bcache lsmod | grep bcache
2. 安装 bcache-tools
bcache-tools
提供了 bcache 设备的管理工具,安装方法如下:文章源自堕落的鱼-https://www.duoluodeyu.com/2791.html
apt install bcache-tools
3. 绑定 SSD 和 HDD
(1)查看硬盘设备
使用 fdisk -l
或 lsblk
查看系统中的存储设备:文章源自堕落的鱼-https://www.duoluodeyu.com/2791.html
lsblk
(2)清除磁盘块信息
确保磁盘没有其他文件系统或分区:文章源自堕落的鱼-https://www.duoluodeyu.com/2791.html
wipefs -a /dev/nvme0n1 # 清除 SSD wipefs -a /dev/sdb # 清除 HDD
(3)创建 bcache 设备
- 创建后端设备(HDD):
make-bcache -B /dev/sdb
- 创建缓存设备(SSD):
make-bcache -C /dev/nvme0n1
(4)确认设备状态
lsblk
可以看到 /dev/bcache0
设备已创建。文章源自堕落的鱼-https://www.duoluodeyu.com/2791.html
(5)绑定缓存设备
首先,获取 SSD 缓存设备的 UUID:文章源自堕落的鱼-https://www.duoluodeyu.com/2791.html
bcache-super-show /dev/nvme0n1
找到 cset.uuid
字段,并将其绑定到后端 HDD:文章源自堕落的鱼-https://www.duoluodeyu.com/2791.html
echo "dcddc3f8-e1d4-4ecf-8510-67158a5e3958" > /sys/block/bcache0/bcache/attach
如果遇到 -bash: echo: write error: No such file or directory
错误,建议重启系统后再次尝试。文章源自堕落的鱼-https://www.duoluodeyu.com/2791.html
4. 配置缓存模式
(1)查看当前缓存状态
cat /sys/block/bcache0/bcache/state
状态可能包括:文章源自堕落的鱼-https://www.duoluodeyu.com/2791.html
no cache
:未绑定缓存设备clean
:缓存正常dirty
:缓存启用回写inconsistent
:数据不一致
(2)更改缓存模式
bcache 主要支持 三种缓存模式:
writethrough
(写通):数据同步写入缓存和数据盘(默认)。writeback
(回写):数据先写入缓存,后续再写入数据盘,性能更高。writearound
(直写):数据直接写入数据盘,仅缓存读取数据。
修改为 回写模式:
echo writeback > /sys/block/bcache0/bcache/cache_mode
5. 格式化并挂载数据盘
(1)格式化数据盘
mkfs.xfs /dev/bcache0
建议使用 XFS 或 ext4 文件系统,以获得更好的性能。
(2)挂载数据盘
临时挂载:
mount /dev/bcache0 /mnt/diskb
设置开机自动挂载:
- 获取 bcache 设备的 UUID:
blkid /dev/bcache0
- 编辑
/etc/fstab
,添加以下内容:
UUID=caa8005f-05ce-430d-b133-94f0a3b32f39 /mnt/diskb xfs defaults 0 0
- 重新挂载:
mount -a
6. 测试性能
使用 fio
进行 I/O 性能测试:
apt install fio
(1)测试 HDD 性能(未使用缓存)
fio -filename=/dev/sdb -direct=1 -iodepth 1 -rw=read -ioengine=psync -bs=4k -size=200G -numjobs=10 -runtime=60 -group_reporting -name=HDD-Test
(2)测试 bcache(启用缓存)
fio -filename=/dev/bcache0 -direct=1 -iodepth 1 -rw=read -ioengine=psync -bs=4k -size=200G -numjobs=10 -runtime=60 -group_reporting -name=BCACHE-Test
(3)测试写入性能
- 无缓存
fio -filename=/dev/sdb -direct=1 -iodepth 1 -rw=randwrite -ioengine=psync -bs=4k -size=200G -numjobs=10 -runtime=60 -group_reporting -name=HDD-WriteTest
- 使用缓存
fio -filename=/dev/bcache0 -direct=1 -iodepth 1 -rw=randwrite -ioengine=psync -bs=4k -size=200G -numjobs=10 -runtime=60 -group_reporting -name=BCACHE-WriteTest
💡 参考:
- bcache 官方文档:https://bcache.evilpiepirate.org/
- Debian Wiki:https://wiki.debian.org/Bcache