메뉴 건너뛰기

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 파일 실행하기

번호 제목 글쓴이 날짜 조회 수
61 small file 한개 파일로 만들기(text file 혹은 parquet file의 테이블) gooper 2022.07.04 76
60 [Cloudera 6.3.4, Kudu]]Service Monitor에서 사용하는 metric중에 일부를 blacklist로 설정하여 모니터링 정보 수집 제외하는 방법 gooper 2022.07.08 31
59 [Kudu]Schema별 혹은 테이블별 사용량(Replica포함) 구하는 방법 gooper 2022.07.14 121
58 [CDP7.1.7]Impala Query의 Memory Spilled 양은 ScratchFileUsedBytes값을 누적해서 구할 수 있다. gooper 2022.07.29 29
57 [kerberos]Kerberos HA구성 참고 페이지 gooper 2022.08.31 15
56 Oracle 12c DB의 LOB타입 컬럼이 있는 테이블을 import할 때 주의 할 사항 gooper 2022.09.14 178
55 [Kerberos인증] /var/log/krb5kdc.log파일 기준으로 인증요청(AS), 티켓확인(TGS)이 진행되는 로그 기록 gooper 2022.09.21 36
54 [impala]쿼리 수행중 발생하는 오류(due to memory pressure: the memory usage of this transaction, Failed to write to server) gooper 2022.10.05 67
53 kerberos연동된 CDH 6.3.4에서 default realm값이 잘못된 상태에서 서비스 기동시 오류 gooper 2022.10.14 35
52 kudu의 내부 table명 변경하는 방법 gooper 2022.11.10 22
51 [oozie]oozie ssh action으로 패스워드 없이 다른 서버에 ssh로그인 하여 shellscript호출하는 설정하는 방법 gooper 2022.11.10 29
50 [Impala 3.2버젼]compute incremental stats db명.테이블명 수행시 ERROR: AnalysisException: Incremental stats size estimate exceeds 2000.00MB. 오류 발생원인및 조치방안 gooper 2022.11.30 697
49 [HA구성 이슈]oozie 2대를 L4로 HA구성했을때 발생하는 이슈 gooper 2023.01.17 17
48 [Kerberos]병렬 kinit 호출시 cache파일이 손상되어 Bad format in credentials cache 혹은 No credentials cache found 혹은 Internal credentials cache error 오류 발생시 gooper 2023.01.20 32
47 [Impala TLS/SSL이슈]RangerAdminRESTClient.java:151] Failed to get response, Error is: TrustManager is not specified gooper 2023.02.02 106
46 [ftgo_application]Unable to infer base url오류 발생시 조치방법 gooper 2023.02.20 1354
45 ./gradlew :composeDown 및 ./gradlew :composeUp 를 성공했을때의 메세지 gooper 2023.02.20 6
44 호출 url현황 gooper 2023.02.21 6
43 [Hive canary]Hive에 Metastore canary red alert및 hive log파일에 Duplicate entry '123456' for key 'NOTIFICATION_LOG_EVENT_ID'가 발생시 조치사항 gooper 2023.03.10 67
42 hive의 메타정보 테이블을 MariaDB로 사용하는 경우 table comment나 column comment에 한글 입력시 깨지는 경우 utf8로 바꾸는 방법. gooper 2023.03.10 93

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.

위로