配置集群时,关于HDFS的配置都在/etc进行了相关配置,用eclipse客户端进行开发时,可以用更高优先级的配置覆盖掉集群中的配置。下面以设置副本为例。
在hadoop集群中hdfs-site.xml的配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<!--nodes-->
<property>
<name>dfs.replication</name>
<value>3</value>
</property>
<!-- 指定Hadoop辅助名称节点主机配置 -->
<property>
<name>dfs.namenode.secondary.http-address</name>
<value>172.17.0.3:50090</value>
</property>
</configuration>
1、采用集群中配置
集群中配置的副本数为3,下面在eclipse中执行上传HDFS文本demo,观察文件的副本数。
@Test
public void testCopyFromLocalFile() throws IOException, InterruptedException, URISyntaxException {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.85.137:9000"), conf, "root");
fs.copyFromLocalFile(new Path("D:/tmp/myfile.txt"), new Path("/user/lzj"));
fs.close();
System.out.println("successfully!");
}
执行demo,发现上传到HDFS中的myfile文件副本的数量为3份。
2、采用classpath下的文件中配置的
把集群配置中的hdfs-site.xml文件复制到src/main/resoures目录下,只保留关于副本的配置即可,src/main/resoures目录下的hdfs-site.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<!--nodes-->
<property>
<name>dfs.replication</name>
<value>2</value>
</property>
</configuration>
然后执行测试demo
@Test
public void testCopyFromLocalFile() throws IOException, InterruptedException, URISyntaxException {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.85.137:9000"), conf, "root");
fs.copyFromLocalFile(new Path("D:/tmp/myfile1.txt"), new Path("/user/lzj"));
fs.close();
System.out.println("successfully!");
}
执行完毕后,发现上传到hdfs中的myfile1.txt的副本数量为2份。说明src/main/resoures目录下的hdfs-site.xml下的配置覆盖掉了集群中副本的配置。
3、采用代码中的配置
保留上面配置,然后在代码中设置副本的数量,代码如下,修改副本设置
@Test
public void testCopyFromLocalFile() throws IOException, InterruptedException, URISyntaxException {
Configuration conf = new Configuration();
conf.set("dfs.replication", "1");
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.85.137:9000"), conf, "root");
fs.copyFromLocalFile(new Path("D:/tmp/myfile2.txt"), new Path("/user/lzj"));
fs.close();
System.out.println("successfully!");
}
执行代码,发现上传到HDFS中myfile2.txt的副本数量为1份,可见代码中副本的设置覆盖掉了src/main/resoures目录下的hdfs-site.xml中副本的配置。
总结
代码中配置优先级高于classpath下的配置,classpath下的配置优先级高于集群中的配置。如果以上三者都没有配置,则采用集群默认的配置。