java api操作远程hadoop集群

来源:互联网 发布:淘宝客服聊天流程 编辑:程序博客网 时间:2024/05/29 16:03

先给个在集群根目录下建立test目录的例子:

String uri="hdfs://ip地址:端口号";Configuration conf = new Configuration();FileSystem fs = FileSystem.get(URI.create(uri),conf);String pathString = "/test";boolean exists = fs.exists(new Path(pathString));if(!exists){    boolean result= fs.mkdirs(new Path(pathString));    System.out.println(result);}

当然了,首先需要导入相对应的jar包,因为我建的是maven工程,因此这里给出依赖项,如果不是用的maven,可以在网上找到相对应的jar包放进去就可以了。

<dependency>    <groupId>org.apache.hadoop</groupId>    <artifactId>hadoop-common</artifactId>    <version>2.7.1</version></dependency>
<dependency>    <groupId>org.apache.hadoop</groupId>    <artifactId>hadoop-hdfs</artifactId>    <version>2.7.1</version></dependency>

运行这段,我发现报错:org.apache.hadoop.security.AccessControlException: org.apache.hadoop.security .AccessControlException: Permission denied: user=jonlen, access=WRITE, inode="hadoop": hadoop:supergroup:rwxr-xr-x。

其实这个错误就是说用户名为jonlen的用户是没有权限在hadoop集群中创建目录,而这个jonlen用户就是当前系统的用户名。大家可能首先会想到把hadoop集群中的配置文件hdfs-site.xml文件中的权限改为false,。大家可以试一下,我试了一下根本行不通,当然也许是我自己设置有问题。

第二种方法就是把hadoop集群中根目录的权限改成可读写,但是这样做也许会有危害,因此不建议这样写。

后来经过研究hadoop的源码,发现在hadoop的登录过程中存在如下代码:

if(!isSecurityEnabled() && (user == null)){

  String envUser = System.getenv(HADOOP_USER_NAME);

if(envUser == null){

     envUser = System.getProperty(HADOOP_USER_NAME);

}

  user = envUser == null ? null:new User(envUser);

}

通过上述代码可以看到hadoop优先读取系统变量,把它作为username,否则读取java环境变量。

说到这里,相信大家都明白了,通俗点说就是配置环境变量。我的做法是在系统环境变量中添加HADOOP_USER_NAME= hadoop(这个值根据实际情况而定,由于我是要访问从linux中上传到hdfs中的文件,因此这个值是登录linux的用户名。)

最后,在重启IDE,运行程序,问题得到解决。


参考文章:http://www.udpwork.com/item/7047.html

                     http://www.cnblogs.com/acmy/archive/2011/10/28/2227901.html



原创粉丝点击