使用HDFS客户端java api读取hadoop集群上的信息

时间:2022-12-17 16:00:41

本文介绍使用hdfs java api的配置方法。

1、先解决依赖,pom

<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.7.2</version>
<scope>provided</scope>
</dependency>

2、配置文件,存放hdfs集群配置信息,基本都是来源于core-site.xml和hdfs-site.xml,可以根据hdfs集群client端配置文件里的信息进行填写

#============== hadoop ===================
hdfs.fs.defaultFS=hdfs://mycluster-tj
hdfs.ha.zookeeper.quorum=XXXX-apache00.XX01,XXXX-apache01.XX01,XXXX-apache02.XX01
hdfs.dfs.nameservices=XXXX
hdfs.dfs.ha.namenodes.mycluster-tj=XX1,XX2
hdfs.dfs.namenode.rpc-address.mycluster-tj.nn1=XXXX-apachenn01.XX01:
hdfs.dfs.namenode.rpc-address.mycluster-tj.nn2=XXXX-apachenn02.XX01:

3、java client api

import java.io.IOException;
import java.net.URI;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.text.SimpleDateFormat;
import java.util.Date; public class HadoopClient {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
private FileSystem fs;
private String defaultFS;
private String zKQuorum;
private String nameServices;
private String nameNodes;
private String rpcAddressNN1;
private String rpcAddressNN2; public void setDefaultFS(String defaultFS) {
this.defaultFS = defaultFS;
}
public String getDefaultFS() {
return defaultFS;
}
public void setZKQuorum(String zKQuorum) {
this.zKQuorum = zKQuorum;
}
public String getzKQuorum() {
return zKQuorum;
}
public void setNameServices(String nameServices) {
this.nameServices = nameServices;
}
public String getNameServices() {
return nameServices;
}
public void setNameNodes(String nameNodes) {
this.nameNodes = nameNodes;
}
public String getNameNodes() {
return nameNodes;
}
public void setRpcAddressNN1(String rpcAddressNN1) {
this.rpcAddressNN1 = rpcAddressNN1;
}
public String getRpcAddressNN1() {
return rpcAddressNN1;
}
public void setRpcAddressNN2(String rpcAddressNN2) {
this.rpcAddressNN2 = rpcAddressNN2;
}
public String getRpcAddressNN2() {
return rpcAddressNN2;
} public void init() {
try {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", defaultFS);
conf.set("ha.zookeeper.quorum", zKQuorum);
conf.set("dfs.nameservice", nameServices);
conf.set("dfs.ha.namenodes.mycluster-tj", nameNodes);
conf.set("dfs.namenode.rpc-address.mycluster-tj.nn1", rpcAddressNN1);
conf.set("dfs.namenode.rpc-address.mycluster-tj.nn2", rpcAddressNN2);
fs = FileSystem.get(new URI(defaultFS), conf);
} catch (Exception ex) {
ex.printStackTrace();
}
} public void stop() {
try {
fs.close();
} catch(Exception e) { }
} public boolean exists(String path) {
boolean isExists = false;
try {
Path hdfsPath = new Path(path);
isExists = fs.exists(hdfsPath);
} catch (Exception ex) {
logger.error("exists error: {}", ex.getMessage());
}
return isExists;
} public String getModificationTime(String path) throws IOException {
String modifyTime = null;
try {
Path hdfsPath = new Path(path);
FileStatus fileStatus = fs.getFileStatus(hdfsPath);
long modifyTimestamp = fileStatus.getModificationTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date(modifyTimestamp);
modifyTime = simpleDateFormat.format(date);
} catch(Exception ex) {
logger.error("getModificationTime error: {}", ex.getMessage());
}
return modifyTime;
} }

4、configuration

import com.xiaoju.dqa.prometheus.client.hadoop.HadoopClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class HadoopConfiguration {
@Value("${hdfs.fs.defaultFS}")
private String defaultFS;
@Value("${hdfs.ha.zookeeper.quorum}")
private String zKQuorum;
@Value("${hdfs.dfs.nameservices}")
private String nameServices;
@Value("${hdfs.dfs.ha.namenodes.mycluster-tj}")
private String nameNodes;
@Value("${hdfs.dfs.namenode.rpc-address.mycluster-tj.nn1}")
private String rpcAddressNN1;
@Value("${hdfs.dfs.namenode.rpc-address.mycluster-tj.nn2}")
private String rpcAddressNN2; @Bean(initMethod = "init", destroyMethod = "stop")
public HadoopClient hadoopClient() {
HadoopClient hadoopClient = new HadoopClient();
hadoopClient.setDefaultFS(defaultFS);
hadoopClient.setZKQuorum(zKQuorum);
hadoopClient.setNameServices(nameServices);
hadoopClient.setNameNodes(nameNodes);
hadoopClient.setRpcAddressNN1(rpcAddressNN1);
hadoopClient.setRpcAddressNN2(rpcAddressNN2);
return hadoopClient;
}
}

今天被一个问题坑的要死了,回来补这篇文章。

如果你要访问的集群采用了viewfs方式管理数据,按照本文上面的方法链接集群是有问题。会导致由URI和nameservices解析成功的namenode才可以访问,而其他的访问不了!!!

如果你想解决这个问题,在api部分你要去掉URI部分和nameservices配置,直接使用集群客户端hdfs-site.xml和core-site.xml

应该是这样的。

package com.xiaoju.dqa.jazz.hadoop.client;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date; public class HadoopClient {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
private FileSystem fs; public void init() {
try {
Configuration conf = new Configuration();
conf.addResource("core-site.xml");
conf.addResource("hdfs-site.xml");
conf.addResource("mount-table.xml");
fs = FileSystem.get(conf);
} catch (Exception ex) {
ex.printStackTrace();
}
} public void stop() {
try {
fs.close();
} catch(Exception e) { }
} public boolean exists(String path) {
boolean isExists = true;
try {
Path hdfsPath = new Path(path);
isExists = fs.exists(hdfsPath);
} catch (Exception e) {
logger.error("[HDFS]判断文件是否存在失败", e);
}
return isExists;
} public String getModificationTime(String path) throws IOException {
String modifyTime = null;
try {
Path hdfsPath = new Path(path);
FileStatus fileStatus = fs.getFileStatus(hdfsPath);
long modifyTimestamp = fileStatus.getModificationTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date(modifyTimestamp);
modifyTime = simpleDateFormat.format(date);
} catch(Exception e) {
logger.error("[HDFS]获取最近修改时间失败", e);
}
return modifyTime;
} public long getPathSize(String path) throws IOException {
long size = -1L;
try {
Path hdfsPath = new Path(path);
size = fs.getContentSummary(hdfsPath).getLength();
} catch (Exception e) {
logger.error("[HDFS]获取路径大小失败", e);
}
return size; } }

config中也不需要传任何参数了

package com.xiaoju.dqa.jazz.hadoop.configuration;

import com.xiaoju.dqa.jazz.hadoop.client.HadoopClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class HadoopConfig { @Bean(initMethod = "init", destroyMethod = "stop")
public HadoopClient hadoopClient() {
HadoopClient hadoopClient = new HadoopClient();
return hadoopClient;
}
}

使用HDFS客户端java api读取hadoop集群上的信息的更多相关文章

  1. 使用hive客户端java api读写hive集群上的信息

    上文介绍了hdfs集群信息的读取方式,本文说hive 1.先解决依赖 <properties> <hive.version>1.2.1</hive.version> ...

  2. 使用JAVA API获取hadoop集群的FileSystem

    所需要配置的参数:  Configuration conf = new Configuration();   conf.set("fs.defaultFS", "hdfs ...

  3. Java接口对Hadoop集群的操作

    Java接口对Hadoop集群的操作 首先要有一个配置好的Hadoop集群 这里是我在SSM框架搭建的项目的测试类中实现的 一.windows下配置环境变量 下载文件并解压到C盘或者其他目录. 链接: ...

  4. Hadoop集群上使用JNI,调用资源文件

    hadoop是基于java的数据计算平台,引入第三方库,例如C语言实现的开发包将会大大增强数据分析的效率和能力. 通常在是用一些工具的时候都要用到一些配置文件.资源文件等.接下来,借一个例子来说明ha ...

  5. &lbrack;转载&rsqb; 把Nutch爬虫部署到Hadoop集群上

    http://f.dataguru.cn/thread-240156-1-1.html 软件版本:Nutch 1.7, Hadoop 1.2.1, CentOS 6.5, JDK 1.7 前面的3篇文 ...

  6. 把Nutch爬虫部署到Hadoop集群上

    原文地址:http://cn.soulmachine.me/blog/20140204/ 把Nutch爬虫部署到Hadoop集群上 Feb 4th, 2014 | Comments 软件版本:Nutc ...

  7. 在Hadoop集群上的HBase配置

    之前,我们已经在hadoop集群上配置了Hive,今天我们来配置下Hbase. 一.准备工作 1.ZooKeeper下载地址:http://archive.apache.org/dist/zookee ...

  8. hadoop 把mapreduce任务从本地提交到hadoop集群上运行

    MapReduce任务有三种运行方式: 1.windows(linux)本地调试运行,需要本地hadoop环境支持 2.本地编译成jar包,手动发送到hadoop集群上用hadoop jar或者yar ...

  9. MapReduce编程入门实例之WordCount:分别在Eclipse和Hadoop集群上运行

    上一篇博文如何在Eclipse下搭建Hadoop开发环境,今天给大家介绍一下如何分别分别在Eclipse和Hadoop集群上运行我们的MapReduce程序! 1. 在Eclipse环境下运行MapR ...

随机推荐

  1. Core Data初试

    CoreDataStack.swift import CoreData class CoreDataStack: NSObject { let context: NSManagedObjectCont ...

  2. Rootkit Hunter Sourcecode Learning

    目录 . Rootkit Hunter Introduce() . Source Code Frame() . do_system_check_initialisation() . do_system ...

  3. hdu 1698 线段树成段更新

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1698 #include <cstdio> #include <cmath> # ...

  4. 浅谈C&plus;&plus; Lambda 表达式(简称LB)

    C++ 11 对LB的支持,对于喜欢Functional Programming的人来说,无疑是超好消息.它使得C++进入了和C#,JavaScript等现代流行的程序设计语言所代表的名人堂. 不熟悉 ...

  5. netback于kthread遇到cpu affinity问题

    最近的升级netback, 在测试过程中,查找vm全双工压力,rx的pps波动很厉害,见rx kthread尽管cpu affinity它是0-7 (dom0 8vcpu), 但往往,她去了物理破坏c ...

  6. 基于python脚本,实现Unity全平台的自动打包

    转载请标明出处:http://www.cnblogs.com/zblade/ 0. 概述 本文主要针对项目中自动打包过程进行调研,实现用python脚本来打出win/android/ios三个平台下的 ...

  7. 08策略模式Strategy

    一.什么是策略模式 Strategy模式也叫策略模式是行为模式之一, 它对一系列的算法加以封装,为所有算法定义一 个抽象的算法接口,并通过继承该抽象算法接口 对所有的算法加以封装和实现,具体的算法选择 ...

  8. EVE-NG硬盘扩容,存储海量镜像

    EVE-NG硬盘扩容,存储海量镜像 来源 http://blog.51cto.com/sms1107/1928453 一.查看当前磁盘使用情况 /dev/mapper/eve--ng--vg-root ...

  9. debug命令

    debug -r 查看寄存器-a 输入指令-t 执形命令 通用寄存器:AX=AH+ALBX=BH+BLCX=CH+CLDX=DH+DL 2Byte 16bitFFFF0-(2的16次方减1) debu ...

  10. 1、v1 与 v2的比较

    1.路由的迁移 /* --- v1 ----*/ .config(function($stateProvider){ $stateProvider .state('main', { url: '/', ...