目录
-
addResource()方法
-
conf.set(“aaa”, “bbb”)
-
hadoop fs -D
Configuration类是hadoop的配置类,而客户端获取配置最常用的方式,就是Java Configuration类的addResource()方法和set()方法。此外,还可以通过shell加 -D 的方式,获取指定配置项。本文将通过以下代码,深入源码,探究Client的配置加载过程。
本次分析,hadoop版本为3.3.4
@Test
public void test2() throws Exception {
Configuration conf = new Configuration();
conf.addResource(new Path("/Users/didi/core-site.xml"));
conf.addResource(new Path("/Users/didi/hdfs-site.xml"));
conf.set("aaa", "bbb");
FsShell shell = new FsShell(conf);
String[] args = {"-D", "ccc=ddd", "-cat", "hdfs://ns1/input/test1.txt"};
int res;
try {
res = ToolRunner.run(shell, args);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
shell.close();
}
System.exit(res);
}
- addResource()方法
我们从conf.addResource(new Path(“/Users/didi/core-site.xml”));开始分析。
(1). addResource()方法有很多重载的方法:
但是,实际上他们都在做同一件事情:新建resource类把这些配置来源包装起来,然后存在resources里。其中,resource是Configuration的内部类,专门用来标记这些配置项来源;resources则是有序存放resource的ArrayList。addResource()方法如下:
public void addResource(Path file) {
addResourceObject(new Resource(file));
}
private synchronized void addResourceObject(Resource resource) {
resources.add(resource); // add to resources
restrictSystemProps |= resource.isParserRestricted();
loadProps(properties, resources.size() - 1, false);
}
(2). 这里,loadProps()方法将resources中除去本次放置的资源外的其他资源全部进行加载:
private synchronized void loadProps(final Properties props,
final int startIdx, final boolean fullReload) {
if (props != null) {
Map backup =
updatingResource != null
? new ConcurrentHashMap<>(updatingResource) : null;
loadResources(props, resources, startIdx, fullReload, quietmode);
if (overlay != null) {
props.putAll(overlay);
if (backup != null) {
for (Map.Entry item : overlay.entrySet()) {
String key = (String) item.getKey();
String[] source = backup.get(key);
if (source != null) {
updatingResource.put(key, source);
}
}
}
}
}
}
代码有两个作用:为加载的属性注明来源和加载已有资源。由于此处不满足加载条件props != null,因此会跳出代码。接下来的流程里还会调用这个方法,我们还会再来分析,主要是分析loadResources()这个加载资源的方法。
conf.addResource(new Path(“/Users/didi/hdfs-site.xml”));同样的方法,不再赘述。
综上,addResource()将资源加入资源列表,如果之前已加载过资源(properties不为空),则加载除了新加资源外的所有资源。
- conf.set(“aaa”, “bbb”)
这个方法的作用为,将key为aaa,value为bbb的属性加载到properties中去。
其中,properties是Configuration的属性,以key-value形式存放已经加载的配置,如dfs.namenode.rpc-address ——> hadoop01:8020。这里写aaa和bbb,纯粹是为了告诉读者,这个key-value是可以随便写的,但是加载过后能否起到作用,就看内部程序有没有定义相关逻辑了。
(1). 再来看conf.set():
public void set(String name, String value, String source) {
Preconditions.checkArgument(
name != null,
“Property name must not be null”);
Preconditions.checkArgument(
value != null,
“The value of property %s must not be null”, name);
name = name.trim();
DeprecationContext deprecations = deprecationContext.get();
if (deprecations.getDeprecatedKeyMap().isEmpty()) {
getProps();
}
getOverlay().setProperty(name, value);
getProps().setProperty(name, value);
String newSource = (source ==