提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
idea上java项目连接hdfs
前言
在开发udf过程中,遇到了需要访问hdfs的情况,开发好udf之后需要在idea上测试,因此需要连接公司的远程Hadoop集群。
提示:以下是本篇文章正文内容,下面案例可供参考
一、本地Hadoop环境配置(需要先有jdk环境)
第一步:下载与服务器上的hadoop同版本的hadoop安装包,解压到某个目录(https://archive.apache.org/dist/hadoop/common/hadoop-3.0.0/)
第二步:配置HADOOP_HOME环境变量,然后重启电脑
%HADOOP_HOME%\bin
第三步:修改hadoop-env.cmd文件的JAVA_HOME为本地的jdk地址
第四步:检验:在dos窗口中输入hadoop
第五步:下载windows下连接hadoop需要的文件hadoop.dll和winutils.exe(https://github.com/cdarlint/winutils/tree/master/hadoop-3.0.2/bin)
(1)将hadoop.dll复制到C:\Windows\System32目录下
(2)将hadoop.dll和winutils.exe复制到F:\hadoop-2.6.0-cdh5.7.0\bin目录下
二、idea配置
1.创建maven,导入pom.xml依赖
pom.xml如下(这几个依赖尽量写上,不然可能报错):
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-common -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-hdfs -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-mapreduce-client-core -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-client-core</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-client -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-yarn-api -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-yarn-api</artifactId>
<version>2.8.5</version>
</dependency>
2.导入集群配置文件
把公司集群里的core-site.xml、hdfs-site.xml、yarn-site.xml这几个文件下载下来,丢到maven项目的resources
3.测试
代码如下(示例):
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.io.IOException;
public class hdfs_test {
public static void main(String[] args) throws IOException {
String filename = "hdfs://nameservice1/user/hive/warehouse/ods_broadband_obd_dtl_df/month_id=202206/";
Configuration conf = new Configuration();
conf.set("fs.defaultFS","hdfs://nameservice1");
FileSystem fs = FileSystem.get(conf);
if (fs.exists(new Path(filename))){
System.out.println("the file is exist");
}else{
System.out.println("the file is not exist");
}
fs.close();
System.out.println("over");
}
}
问题
遇到没有权限访问hdfs路径的情况:Permission denied: user=administrator, access=WRITE
在系统的环境变量里面添加HADOOP_USER_NAME=hadoop(HDFS上的有权限的用户,具体看自己的情况),修改完环境变量后,记得重启一下idea
参考:https://blog.csdn.net/zhangjunli/article/details/106321516