本文是大数据系列第 8 篇,在理解 HDFS 读写原理后,上机实操 hadoop fs 命令行工具。
前提:启动集群
start-dfs.sh
start-yarn.sh
确认三个 DataNode 在线:http://h121.wzk.icu:50070
命令格式
HDFS 命令有两种等价写法:
hdfs dfs -<命令> [选项] [参数]
hadoop fs -<命令> [选项] [参数] # 旧写法,效果相同
目录操作
# 列出目录(-h 显示文件大小为人类可读格式)
hdfs dfs -ls /
hdfs dfs -ls -h /user
# 创建目录(-p 递归创建)
hdfs dfs -mkdir /test
hdfs dfs -mkdir -p /test/2024/07
# 删除目录(-r 递归删除,-skipTrash 跳过回收站)
hdfs dfs -rm -r /test/2024
文件上传
# 上传(保留本地文件)
hdfs dfs -put /local/file.txt /hdfs/path/
# 移动上传(上传后删除本地文件)
hdfs dfs -moveFromLocal /local/file.txt /hdfs/path/
# 从 stdin 写入(适合小文件)
echo "hello" | hdfs dfs -put - /test/hello.txt
文件下载
# 下载到本地
hdfs dfs -get /hdfs/file.txt /local/path/
# 复制到本地(同 get)
hdfs dfs -copyToLocal /hdfs/file.txt /local/path/
# 查看文件内容
hdfs dfs -cat /test/hello.txt
hdfs dfs -tail /test/bigfile.txt # 查看末尾
文件管理
# HDFS 内部复制
hdfs dfs -cp /src/file.txt /dst/
# HDFS 内部移动/重命名
hdfs dfs -mv /old.txt /new.txt
# 删除文件
hdfs dfs -rm /test/file.txt
# 删除并跳过回收站
hdfs dfs -rm -skipTrash /test/file.txt
查看文件信息
# 统计目录大小
hdfs dfs -du -h /test
# 统计目录文件数
hdfs dfs -count /test
# 查看 Block 信息
hdfs fsck /test/file.txt -files -blocks -locations
权限管理
# 修改权限(类似 chmod)
hdfs dfs -chmod 755 /test
# 修改所有者
hdfs dfs -chown hadoop:hadoop /test
# 递归修改
hdfs dfs -chmod -R 755 /test
合并小文件下载
多个小文件合并下载到本地:
hdfs dfs -getmerge /test/input/ /local/merged.txt
Secondary NameNode 机制
NameNode 在内存中维护 FsImage(元数据快照)和 EditLog(操作日志)。Secondary NameNode 的职责:
- 定期从 NameNode 下载 FsImage 和 EditLog
- 将 EditLog 合并到 FsImage,生成新的 FsImage
- 上传新 FsImage 到 NameNode
这避免了 EditLog 无限增长导致 NameNode 重启时间过长。