Hadoop 获取Active Namenode的IP地址

       由于工作需要,需要拿到当前集群的Active Namenode的Ip地址,所以写以下小代码,防止忘记,记录一下:

import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.HAUtil;

public class ActiveNNAdd {

public void getNameNodeAdress() throws Exception {
Configuration conf = new Configuration();

FileSystem system = null;
try {
    system = FileSystem.get(conf);
    InetSocketAddress active = HAUtil.getAddressOfActive(system);
    System.out.println(active.getHostString()); 
    // System.out.println("hdfs port:" + active.getPort());
    // InetAddress address = active.getAddress();
    // System.out.println("hdfs://" + address.getHostAddress() + ":"+ active.getPort()); 
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (system != null) {
            system.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


public static void main(String[] args) {

ActiveNNAdd nn = new ActiveNNAdd() ;

try {
    nn.getNameNodeAdress();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
}

  以上代码是使用Hadoop源码提供的HAUtil工具类来做的,有兴趣的小伙伴还可以尝试连接Zookeeper获取!

你可能感兴趣的:(大数据)