首頁 > 軟體

利用Java連線Hadoop進行程式設計

2022-06-28 18:01:28

實驗環境

  • hadoop版本:3.3.2
  • jdk版本:1.8
  • hadoop安裝系統:ubuntu18.04
  • 程式設計環境:IDEA
  • 程式設計主機:windows

實驗內容

測試Java遠端連線hadoop

建立maven工程,引入以下依賴:

<dependency>
                <groupId>org.testng</groupId>
                <artifactId>testng</artifactId>
                <version>RELEASE</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-common</artifactId>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-hdfs</artifactId>
                <version>3.3.2</version>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-common</artifactId>
                <version>3.3.2</version>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-core</artifactId>
                <version>1.2.1</version>
            </dependency>

虛擬機器器的/etc/hosts設定

hdfs-site.xml設定

<configuration>
        <property>
                <name>dfs.replication</name>
                <value>1</value>
        </property>
        <property>
                <name>dfs.namenode.name.dir</name>
                <value>file:/root/rDesk/hadoop-3.3.2/tmp/dfs/name</value>
        </property>
        <property>
                <name>dfs.datanode.http.address</name>
                <value>VM-12-11-ubuntu:50010</value>
        </property>
        <property>
                <name>dfs.client.use.datanode.hostname</name>
                <value>true</value>
        </property>
        <property>
                <name>dfs.datanode.data.dir</name>
                <value>file:/root/rDesk/hadoop-3.3.2/tmp/dfs/data</value>
        </property>
</configuration>

core-site.xml設定

<configuration>
  <property>
          <name>hadoop.tmp.dir</name>
          <value>file:/root/rDesk/hadoop-3.3.2/tmp</value>
          <description>Abase for other temporary directories.</description>
  </property>
  <property>
          <name>fs.defaultFS</name>
          <value>hdfs://VM-12-11-ubuntu:9000</value>
  </property>
</configuration>

啟動hadoop

sbin/start-dfs.sh

主機的hosts(C:WindowsSystem32driversetc)檔案設定

嘗試連線到虛擬機器器的hadoop並讀取檔案內容,這裡我讀取hdfs下的/root/iinput檔案內容

Java程式碼:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DistributedFileSystem;
public class TestConnectHadoop {
    public static void main(String[] args) throws Exception {

        String hostname = "VM-12-11-ubuntu";
        String HDFS_PATH = "hdfs://" + hostname + ":9000";
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", HDFS_PATH);
        conf.set("fs.hdfs.impl", DistributedFileSystem.class.getName());
        conf.set("dfs.client.use.datanode.hostname", "true");

        FileSystem fs = FileSystem.get(conf);
        FileStatus[] fileStatuses = fs.listStatus(new Path("/"));
        for (FileStatus fileStatus : fileStatuses) {
            System.out.println(fileStatus.toString());
        }
        FileStatus fileStatus = fs.getFileStatus(new Path("/root/iinput"));
        System.out.println(fileStatus.getOwner());
        System.out.println(fileStatus.getGroup());

        System.out.println(fileStatus.getPath());
        FSDataInputStream open = fs.open(fileStatus.getPath());
        byte[] buf = new byte[1024];
        int n = -1;
        StringBuilder sb = new StringBuilder();
        while ((n = open.read(buf)) > 0) {
            sb.append(new String(buf, 0, n));
        }
        System.out.println(sb);
    }
}

執行結果:

程式設計實現一個類“MyFSDataInputStream”,該類繼承“org.apache.hadoop.fs.FSDataInputStream",要求如下: ①實現按行讀取HDFS中指定檔案的方法”readLine()“,如果讀到檔案末尾,則返回為空,否則返回檔案一行的文字

思路:emmm我的思路比較簡單,只適用於該要求,僅作參考。
將所有的資料讀取出來儲存起來,然後根據換行符進行拆分,將拆分的字串陣列儲存起來,用於readline返回

Java程式碼

import org.apache.hadoop.fs.FSDataInputStream;
import java.io.IOException;
import java.io.InputStream;
public class MyFSDataInputStream extends FSDataInputStream {
    private String data = null;
    private String[] lines = null;
    private int count = 0;
    private FSDataInputStream in;
    public MyFSDataInputStream(InputStream in) throws IOException {
        super(in);
        this.in = (FSDataInputStream) in;
        init();
    }
    private void init() throws IOException {
        byte[] buf = new byte[1024];
        int n = -1;
        StringBuilder sb = new StringBuilder();
        while ((n = this.in.read(buf)) > 0) {
            sb.append(new String(buf, 0, n));
        }
        data = sb.toString();
        lines = data.split("n");
    }
    /**
     * 實現按行讀取HDFS中指定檔案的方法」readLine()「,如果讀到檔案末尾,則返回為空,否則返回檔案一行的文字
     */
    public String read_line() {
        return count < lines.length ? lines[count++] : null;
    }

}

測試類:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DistributedFileSystem;
public class TestConnectHadoop {
    public static void main(String[] args) throws Exception {

        String hostname = "VM-12-11-ubuntu";
        String HDFS_PATH = "hdfs://" + hostname + ":9000";
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", HDFS_PATH);
        conf.set("fs.hdfs.impl", DistributedFileSystem.class.getName());
        conf.set("dfs.client.use.datanode.hostname", "true");
        FileSystem fs = FileSystem.get(conf);
        FileStatus fileStatus = fs.getFileStatus(new Path("/root/iinput"));
        System.out.println(fileStatus.getOwner());
        System.out.println(fileStatus.getGroup());
        System.out.println(fileStatus.getPath());
        FSDataInputStream open = fs.open(fileStatus.getPath());
        MyFSDataInputStream myFSDataInputStream = new MyFSDataInputStream(open);
        String line = null;
        int count = 0;
        while ((line = myFSDataInputStream.read_line()) != null ) {
            System.out.printf("line %d is: %sn", count++, line);
        }
        System.out.println("end");

    }
}

執行結果:

②實現快取功能,即利用”MyFSDataInputStream“讀取若干位元組資料時,首先查詢快取,如果快取中有所需要資料,則直接由快取提供,否則從HDFS中讀取資料

import org.apache.hadoop.fs.FSDataInputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
public class MyFSDataInputStream extends FSDataInputStream {
    private BufferedInputStream buffer;
    private String[] lines = null;
    private int count = 0;
    private FSDataInputStream in;
    public MyFSDataInputStream(InputStream in) throws IOException {
        super(in);
        this.in = (FSDataInputStream) in;
        init();
    }
    private void init() throws IOException {
        byte[] buf = new byte[1024];
        int n = -1;
        StringBuilder sb = new StringBuilder();
        while ((n = this.in.read(buf)) > 0) {
            sb.append(new String(buf, 0, n));
        }
        //快取資料讀取
        buffer = new BufferedInputStream(this.in);
        lines = sb.toString().split("n");
    }
    /**
     * 實現按行讀取HDFS中指定檔案的方法」readLine()「,如果讀到檔案末尾,則返回為空,否則返回檔案一行的文字
     */
    public String read_line() {
        return count < lines.length ? lines[count++] : null;
    }
    @Override
    public int read() throws IOException {
        return this.buffer.read();
    }
    public int readWithBuf(byte[] buf, int offset, int len) throws IOException {
        return this.buffer.read(buf, offset, len);
    }
    public int readWithBuf(byte[] buf) throws IOException {
        return this.buffer.read(buf);
    }
}

到此這篇關於利用Java連線Hadoop進行程式設計的文章就介紹到這了,更多相關Java連線Hadoop內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com