Hadoop 版本:hadoop-2.6.0-cdh5.15.1
虽然在hdfs-site.xml中设置了副本数量:
<property>
<name>dfs.replication</name>
<value>1</value>
</property>
但是我们在Java API代码中创建文件:
public class HDFSAPP {
public static final String HDFS_PATH = "hdfs://swarm-worker1:9000";
FileSystem fileSystem = null;
Configuration configuration = null;
/**
* 构造一个访问指定HDFS系统的客户端对象
* 第一个参数:HDFS的URI
* 第二个参数:客户端指定的配置参数
* 第三个参数:客户端的身份,即用户名
* @throws URISyntaxException
*/
@Before
public void setUp() throws URISyntaxException, IOException, InterruptedException {
System.out.println("--------setUp---------");
configuration = new Configuration();
fileSystem = FileSystem.get(new URI("hdfs://swarm-worker1:9000"), configuration, "iie4bu");
}
/**
* 创建文件
* @throws Exception
*/
@Test
public void create() throws Exception {
FSDataOutputStream out = fileSystem.create(new Path("/hdfsapi/test/a.txt"));
out.writeUTF("hello world");
out.flush();
out.close();
}
@After
public void tearDown() {
configuration = null;
fileSystem = null;
System.out.println("--------tearDown---------");
}
}
上面的代码创建了一个文件/hdfsapi/test/a.txt
,在浏览器中查看:
可以看到副本数量Replication为3,而我们通过命令创建的文件副本数量是1。
说明是在代码层面有一个默认设置。
@Test
public void testReplication() {
System.out.println(configuration.get("dfs.replication"));
}
上面的代码输出结果为3
说明副本数量是3。
在这个路径下有一个hdfs-default.xml
文件,文件中指定了默认的replication数量是3:
这就是为什么configuration默认的数量是3的原因了。因为我们使用的configuration是默认的,自动加载默认的hdfs-default.xml
文件中的数据。
所以我们可以通过手动设置这个参数来修改replication:
configuration.set("dfs.replication", "1");
此时再创建一个文件时,replication副本数量就是1了。