Hadoop 入門教程

Hadoop 教程

1. 前期準(zhǔn)備

2. HDFS啟動(dòng)

cd app/hadoop-2.6.0-cdh5.7.0/sbin/
./start-dfs.sh 
在這里插入圖片描述

3. Hadoop啟動(dòng)失敗解決方法

  • 重新編輯本機(jī)的hosts文件
    sudo vim /etc/hosts
    
  • hadoop000localhost 均改為本機(jī)ip
    在這里插入圖片描述

    在這里插入圖片描述

4. Hadoop Shell命令

  • 瀏覽器可視化文件系統(tǒng)


    在這里插入圖片描述
  • 路徑遍歷
    • hadoop fs -ls [路徑]
  • 查看文件
    • hadoop fs -cat [文件路徑]
    • eg:hadoop fs -cat /hadoopruochen/test/ruochen.txt
  • 新建文件夾
    • hadoop fs -mkdir -p [路徑]
    • -p:遞歸新建
    • eg:hadoop fs -mkdir -p /hadoopruochen/test
  • 傳文件到 Hadoop
    • hadoop fs -put [文件路徑] [hadoop路徑]
    • eg:hadoop fs -put ruochen.txt /hadoopruochen/test
  • 下載 Hadoop 文件到本地
    • hadoop fs -get [hadoop文件路徑] [本地路徑]
    • eg:hadoop fs -get /hadoopruochen/test/ruochen.txt haha.txt
  • 移動(dòng)文件
    • hadoop fs -mv [源路徑] [目的路徑]
    • eg:hadoop fs -mv /hadoopruochen/test/ruochen.txt /user
  • 刪除文件
    • hadoop fs -rm [-r] [文件]
    • eg:hadoop fs -rm /hadoopruochen
    • eg:hadoop fs -rm -r /hadoopruochen

5. Java 操作 HDFS API

5.1. 新建項(xiàng)目

  • 新建一個(gè)空項(xiàng)目,我這里起名為BigData
    在這里插入圖片描述
  • 新建一個(gè)module


    在這里插入圖片描述

    在這里插入圖片描述

    在這里插入圖片描述
  • Finish 即可
  • pom.xml如下
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.neusoft</groupId>
    <artifactId>hadoopdemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>hadoopdemo</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <hadoop.version>2.6.0-cdh5.7.0</hadoop.version>
    </properties>
    <repositories>
        <repository>
            <id>cloudera</id>
            <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
        </repository>
    </repositories>

    <dependencies>
        <!--        添加hadoop依賴-->
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>${hadoop.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
                <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
                <plugin>
                    <artifactId>maven-site-plugin</artifactId>
                    <version>3.7.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-project-info-reports-plugin</artifactId>
                    <version>3.0.0</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

5.2. 測(cè)試

5.2.1 新建文件夾

  • 接下來(lái),我們使用 Java 連接 hdfs,并新建一個(gè)文件夾
  • 在test下新建HDFSApp.java,如下
    在這里插入圖片描述
  • 通過(guò)測(cè)試方法連接HDFS,并新建一個(gè)/ruochen/test2文件夾,代碼如下
    package com.neusoft.hdfs;
    
    import org.apache.hadoop.fs.FileSystem;
    import org.apache.hadoop.fs.Path;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import org.apache.hadoop.conf.Configuration;
    
    import java.net.URI;
    
    public class HDFSApp {
        Configuration configuration = null;
        FileSystem fileSystem = null;
        public static final String HDFS_PATH = "hdfs://192.168.10.128:8020";
    
        @Test
        public void mkdir() throws Exception {
            fileSystem.mkdirs(new Path("/ruochen/test2"));
        }
    
        // Java 連接hdfs 需要先建立一個(gè)連接
        // 測(cè)試方法執(zhí)行之前要執(zhí)行的操作
        @Before
        public void setUp() throws Exception {
            System.out.println("開始建立與HDFS的連接");
            configuration = new Configuration();
            fileSystem = FileSystem.get(new URI(HDFS_PATH), configuration, "hadoop");
        }
    
        // 測(cè)試之后要執(zhí)行的代碼
        @After
        public void tearDown() {
            configuration = null;
            fileSystem = null;
            System.out.println("關(guān)閉與HDFS的連接");
        }
    }
    
    
  • 然后運(yùn)行mkdir()函數(shù),運(yùn)行完后我們可以看到已經(jīng)新建了一個(gè)文件夾
    在這里插入圖片描述

5.2.2 新建文件

  • 新建文件代碼如下
        // 創(chuàng)建文件
        @Test
        public void create() throws Exception {
            Path path = new Path("/ruochen/test1/hello.txt");
            FSDataOutputStream outputStream = fileSystem.create(path);
            outputStream.write("hello world".getBytes());
            outputStream.flush();
            outputStream.close();
        }
    
  • 運(yùn)行結(jié)束后,我們通過(guò)shell腳本查看一下


    在這里插入圖片描述

5.2.3 修改文件名稱

  • Java代碼如下
       // rename文件
       @Test
       public void rename() throws Exception {
           Path oldPath = new Path("/ruochen/test1/hello.txt");
           Path newPath = new Path("/ruochen/test1/xixi.txt");
           fileSystem.rename(oldPath, newPath);
       }
    
  • 運(yùn)行結(jié)果如下


    在這里插入圖片描述

5.2.4 查看文件

  • Java代碼如下
        // 查看文件
        @Test
        public void cat() throws Exception {
            Path path = new Path("/ruochen/test1/xixi.txt");
            FSDataInputStream inputStream = fileSystem.open(path);
            IOUtils.copyBytes(inputStream, System.out, 1024);
            inputStream.close();
        }
    
  • 運(yùn)行結(jié)果


    在這里插入圖片描述

5.2.5 上傳文件

  • Java 代碼如下
        // 上傳文件
        @Test
        public void upload() throws Exception {
            Path localPath = new Path("cifar-10-python.tar.gz");
            Path hdfsPath = new Path("/");
            fileSystem.copyFromLocalFile(localPath, hdfsPath);
        }
    
  • 運(yùn)行完成后,我們可以看到 hdfs 已經(jīng)成功顯示剛才上傳的文件


    在這里插入圖片描述

5.2.6 下載文件

  • Java 代碼
        // 下載文件
        @Test
        public void download() throws Exception {
            Path hdfsPath = new Path("/hadoop-2.6.0-cdh5.7.0.tar.gz");
            Path localPath = new Path("./down/hadoop-2.6.0-cdh5.7.0.tar.gz");
            fileSystem.copyToLocalFile(false, hdfsPath, localPath, true);
        }
    
  • 運(yùn)行完后我們可以看到當(dāng)前目錄 down 下已經(jīng)有了剛剛下載的文件


    在這里插入圖片描述

    在這里插入圖片描述

6. Java 實(shí)現(xiàn) WordCount

  • 新建一個(gè) WordCountApp

    在這里插入圖片描述

  • Java 代碼如下

    package com.neusoft;
    
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.FileSystem;
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.io.LongWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Job;
    import org.apache.hadoop.mapreduce.Mapper;
    import org.apache.hadoop.mapreduce.Reducer;
    import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
    import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
    
    import java.io.IOException;
    
    /**
     * 詞頻統(tǒng)計(jì)
     */
    public class WordCountApp {
        /**
         * map 階段
         */
        public static class MyMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
            LongWritable one = new LongWritable(1);
    
            @Override
            protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
                // 分
                String line = value.toString();
                // 拆分
                String[] s = line.split(" ");
                for (String word : s) {
                    // 輸出
                    context.write(new Text(word), one);
                }
            }
        }
    
        /**
         * reduce 階段
         */
        public static class MyReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
            @Override
            protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
                long sum = 0;
                // 合并統(tǒng)計(jì)
                for (LongWritable value : values) {
                    // 求和
                    sum += value.get();
                }
                context.write(key, new LongWritable(sum));
            }
        }
    
        public static void main(String[] args) throws Exception {
            Configuration configuration = new Configuration();
            Job job = Job.getInstance(configuration, "wordcount");
            job.setJarByClass(WordCountApp.class);
    
            // 設(shè)置 map 相關(guān)參數(shù)
            FileInputFormat.setInputPaths(job, new Path(args[0]));
            job.setMapperClass(MyMapper.class);
            job.setMapOutputKeyClass(Text.class);
            job.setMapOutputValueClass(LongWritable.class);
    
            // 設(shè)置 reduce 相關(guān)參數(shù)
            job.setReducerClass(MyReducer.class);
            job.setOutputKeyClass(MyReducer.class);
            job.setOutputValueClass(LongWritable.class);
    
            Path outPath = new Path(args[1]);
            FileSystem fileSystem = FileSystem.get(configuration);
            if (fileSystem.exists(outPath)) {
                // 刪除文件
                fileSystem.delete(outPath, true);
                System.out.println("輸出路徑已存在, 已被刪除");
            }
            FileOutputFormat.setOutputPath(job, outPath);
    
            // 控制臺(tái)輸出詳細(xì)信息
            // 輸出:1  不輸出:0
            System.exit(job.waitForCompletion(true) ? 0 : 1);
        }
    }
    
    
  • 打包程序


    在這里插入圖片描述

    在這里插入圖片描述
  • 打包完成后,將 jar 包上傳到 hadoop 虛擬機(jī)


    在這里插入圖片描述

    在這里插入圖片描述
  • 首先通過(guò)shell命令將輸出文件夾刪除,不然重復(fù)執(zhí)行會(huì)報(bào)錯(cuò)

    hadoop fs -rm -r /output/wc
    
  • 然后執(zhí)行下列操作

    hadoop jar hadoopdemo-1.0-SNAPSHOT.jar com.neusoft.WordCountApp hdfs://hadoop000:8020/ruochenchen.txt hdfs://hadoop000:8020/output/wc
    

    hadoop jar hadoopdemo-1.0-SNAPSHOT.jar com.neusoft.WordCountApp 輸入文件 輸出文件

    在這里插入圖片描述
  • 然后我們可以看到作業(yè)中有顯示


    在這里插入圖片描述
  • 通過(guò) cat 命令可以查看一下輸出的文件

    在這里插入圖片描述

    hadoop fs -cat /output/wc/part-r-00000
    
    在這里插入圖片描述
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容