메뉴 건너뛰기

Bigdata, Semantic IoT, Hadoop, NoSQL

Bigdata, Hadoop ecosystem, Semantic IoT등의 프로젝트를 진행중에 습득한 내용을 정리하는 곳입니다.
필요한 분을 위해서 공개하고 있습니다. 문의사항은 gooper@gooper.com로 메일을 보내주세요.


Hadoop Hadoop wordcount 소스 작성

구퍼 2013.03.06 10:42 조회 수 : 1888

Hadoop wordcount 소스 작성

Hadoop (하둡) wordcount 예제 소스를 작성해보자.

본 포스팅에서는 이클립스에서 maven 프로젝트를 생성하여 작성하는 것으로

maven 설치가 안되어있다면 이전포스팅을 참고하기 바람.

메이븐 (maven) 설치 및 이클립스 연동하기 쉬운설명

하둡설치도 안되있다면..

Hadoop(하둡) 설치 및 시작 따라하기

메이븐으로 하둡 프로젝트 생성하기

이클립스 상단메뉴에서

'File - New - Other' 를 클릭하여 프로젝트 생성창을 띄운 뒤

'Maven - Maven Project'를 선택한다.

Next 클릭~

'Create a simple project' 에 체크를 하고 Next 버튼을 누른다.

Group Id 와 Artifact Id 을 입력한다.

Group Id 는 패키지 네임, Artifact Id 는 프로젝트 네임 이라고 생각하면 된다.

Finish 를 누르면 프로젝트가 생성된다.

다음으로

하둡은 java 1.6 이상의 버전을 요구하기 때문에 JRE System Library 를 변경해 주어야 한다.

생성된 프로젝트에서 'JRE System Library' 를 우클릭 하고 'Properties' 를 클릭하면 아래와 같은 창이뜬다.

System library 에서 'Alternate JRE' 를 체크한 후 JDK 1.6 이상으로 설정한다.

다음으로 Maven Dependencies 에 라이브러리를 추가하여야 한다.

생성한 프로젝트를 우클릭하여 나타난 메뉴에서 'Maven - Add Dependency' 를 클릭한다.

Add Dependency 창이 나타나면 'org.apache.hadoop' 를 검색하여 hadoop-core 를 추가하여야 한다.

hadoop-core 버전은 본인이 설치한 hadoop의 버전으로 선택하면 된다.

wordcount 소스 작성하기

이제 wordcount 소스를 작성하도록 하겠다.

'src/test/java 우클릭 - New - Package' 를 차례로 클릭하여 패키지 생성창을 띄우고

Package 네임을 입력하여 (위 그림의 kr.bigmark.wordcount) 생성한다.

패키지가 생성되었으면

'생성된 패키지를 우클릭하고 New - Class' 를 선택하여 자바 클래스를 생성한다.

Class 생성 창에서 'Name : WordCount' 를 입력하고 Finish~

소스작성 전 모든 준비가 마무리되면 위 그림과 같은

구조로 나타날 것이다.

자 그럼 wordcount 소스를 코딩하자.

아래의 소스가 wordcount 소스이니 참고하고, package 네임은 본인 패키지에 맞게 변경할 것.

package kr.bigmark.wordcount;

import java.io.IOException;
import java.util.*;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;

@SuppressWarnings("unused")
public class WordCount {
public static class Map extends MapReduceBase
implements Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();

public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output,
Reporter reporter) throws IOException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
output.collect(word, one);
}
}
}

public static class Reduce extends MapReduceBase
implements Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterator<IntWritable> values,
OutputCollector<Text, IntWritable> output,
Reporter reporter) throws IOException {
int sum = 0;
while (values.hasNext()) {
sum += values.next().get();
}
output.collect(key, new IntWritable(sum));
}
}

public static void main(String[] args) throws Exception {
JobConf conf = new JobConf(WordCount.class);
conf.setJobName("wordcount");

conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(IntWritable.class);

conf.setMapperClass(Map.class);
conf.setCombinerClass(Reduce.class);
conf.setReducerClass(Reduce.class);

conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);

FileInputFormat.setInputPaths(conf, new Path(args[0]));
FileOutputFormat.setOutputPath(conf, new Path(args[1]));

JobClient.runJob(conf);
}
}

소스 작성이 완료 되면 jar 파일을 Export 하여 마무리 한다.

jar 파일 Export 하는 방법은

프로젝트 우클릭 - Export 를 누르고 Java - JAR file 를 선택한다.

작성한 프로젝트인 'ExWordCount' 에 체크가 되어있는지 확인하고

Select the export destination 에서 'Browse' 버튼을 눌러 jar 파일을 생성할 경로를 입력한다.

Finish 버튼을 누르면 해당경로에 wordcount 의 jar 파일이 생성된 것을 확인 할 수 있을 것이다.

생성한 wordcount.jar 파일 실행방법은 다음 포스팅을 참조하시길~

hadoop (하둡) 이클립스에서 생성한 jar 파일 실행하기

번호 제목 글쓴이 날짜 조회 수
60 [Cloudera 6.3.4, Kudu]]Service Monitor에서 사용하는 metric중에 일부를 blacklist로 설정하여 모니터링 정보 수집 제외하는 방법 gooper 2022.07.08 31
59 Cloudera Manager의 Java Heap Size변경하는 방법 gooper 2022.06.27 31
58 federated query 예제 총관리자 2017.01.19 31
57 [KTS Cluster의 Key Trustee Server]self-signed 인증서 발급및 설정 방법 gooper 2023.06.27 29
56 [oozie]oozie ssh action으로 패스워드 없이 다른 서버에 ssh로그인 하여 shellscript호출하는 설정하는 방법 gooper 2022.11.10 29
55 [CDP7.1.7]Impala Query의 Memory Spilled 양은 ScratchFileUsedBytes값을 누적해서 구할 수 있다. gooper 2022.07.29 29
54 Could not authenticate, GSSException: No valid credentials provided (Mechanism level: Failed to find any kerberos tgt) 총관리자 2022.04.28 27
53 Oracle RAC 구성된 DB서버에 대한 컴포넌트별 설정 방법 총관리자 2022.02.12 27
52 [vi]블럭 및 문서내 복사등에 관련된 명령어 총관리자 2017.02.17 27
51 Error: IO_ERROR : java.io.IOException: Error while connecting Oozie server 총관리자 2022.05.02 26
50 kudu table와 impala(hive) table정보가 틀어져서 테이블을 읽지 못하는 경우(Error Loading Metadata) 조치방법 gooper 2023.11.10 25
49 클러스터내의 전체 workflow및 coordinator현황을 사용자별로 추출하는 방법 총관리자 2021.11.25 25
48 oracle 접속 방식에 따른 --connect 지정 방법 총관리자 2022.02.11 24
47 hadoop에서 yarn jar ..를 이용하여 appliction을 실행하여 정상적으로 수행되었으나 yarn UI의 어플리케이션 목록에 나타나지 않는 문제 총관리자 2017.05.02 24
46 magento2 샘플데이타 설치 총관리자 2017.01.31 24
45 [Ranger]RangerAdminRESTClient Error gertting pplicies; Received NULL response!!, secureMode=true, user=rangerkms/node01.gooper.com@ GOOPER.COM (auth:KERBEROS), serviceName=cm_kms gooper 2023.06.27 23
44 [Solr in Cloudera]Solr Data Directory변경 방법/절차 gooper 2023.04.21 23
43 vuestorefrontui.io를 이용한 front end project 생성하기 총관리자 2022.02.06 23
42 not leader of this config: current role FOLLOWER 오류 발생시 확인방법 총관리자 2022.01.17 23
41 kudu의 내부 table명 변경하는 방법 gooper 2022.11.10 22

A personal place to organize information learned during the development of such Hadoop, Hive, Hbase, Semantic IoT, etc.
We are open to the required minutes. Please send inquiries to gooper@gooper.com.

위로