메뉴 건너뛰기

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

번호 제목 글쓴이 날짜 조회 수
740 bananapi 5대(ubuntu계열 리눅스)에 yarn(hadoop 2.6.0)설치하기-ResourceManager HA/HDFS HA포함, JobHistory포함 총관리자 2015.04.24 19143
739 mapreduce appliction을 실행시 "is running beyond virtual memory limits" 오류 발생시 조치사항 총관리자 2017.05.04 16899
738 org.apache.hadoop.hdfs.server.common.InconsistentFSStateException: Directory /tmp/hadoop-root/dfs/name is in an inconsistent state: storage directory does not exist or is not accessible. 구퍼 2013.03.11 14781
737 drop table로 삭제했으나 tablet server에는 여전히 존재하는 테이블 삭제방법 총관리자 2021.07.09 7554
736 insert hbase by hive ... error occured after 5 hours..HMaster가 뜨지 않는 장애에 대한 복구 방법 총관리자 2014.04.29 7129
735 Resource temporarily unavailable(자원이 일시적으로 사용 불가능함) 오류조치 총관리자 2015.11.19 6859
734 HBase shell로 작업하기 구퍼 2013.03.15 5834
733 dr.who로 공격들어오는 경우 조치방법 file 총관리자 2018.06.09 5603
732 하둡 분산 파일 시스템을 기반으로 색인하고 검색하기 구퍼 2013.03.15 5573
731 [Decommission]시 시간이 많이 걸리면서(수일) Decommission이 완료되지 않는 경우 조치 총관리자 2018.01.03 5325
730 Ubuntu 16.04LTS 설치후 초기에 주어야 하는 작업(php, apache, mariadb설치및 OS보안설정등) file 총관리자 2017.05.23 5271
729 hive 2.0.1 설치및 mariadb로 metastore 설정 총관리자 2016.06.03 5184
728 Hive Query Examples from test code (2 of 2) 총관리자 2014.03.26 5013
727 Spark에서 Serializable관련 오류및 조치사항 총관리자 2017.04.21 4901
726 [gson]mongodb의 api를 이용하여 데이타를 가져올때 "com.google.gson.stream.MalformedJsonException: Unterminated object at line..." 오류발생시 조치사항 총관리자 2017.12.11 4415
725 import 혹은 export할때 hive파일의 default 구분자는 --input-fields-terminated-by "x01"와 같이 지정해야함 총관리자 2014.05.20 4245
724 checking for termcap functions library... configure: error: No curses/termcap library found 구퍼 2013.03.08 4120
723 sqoop작업시 hdfs의 개수보다 더많은 값이 중복되어 oracle에 입력되는 경우가 있음 총관리자 2014.09.02 4093
722 다수의 로그 에이전트로 부터 로그를 받아 각각의 파일로 저장하는 방법(interceptor및 multiplexing) 총관리자 2014.04.04 4089
721 .git폴더를 삭제하고 다시 git에 추가하고 서버에 반영하는 방법 총관리자 2017.06.19 4077

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.

위로