有時候我們在項目中會遇到輸入結果集很大,但是輸出結果很小,比如一些 pv、uv 數據,然后為了實時查詢的需求,或者一些 OLAP 的需求,我們需要 mapreduce 與 mysql 進行數據的交互,而這些特性正是 hbase 或者 hive 目前亟待改進的地方。
好了言歸正傳,簡單的說說背景、原理以及需要注意的地方:
1、為了方便 MapReduce 直接訪問關系型數據庫(Mysql,Oracle),Hadoop提供了DBInputFormat和DBOutputFormat兩個類。通過DBInputFormat類把數據庫表數據讀入到HDFS,根據DBOutputFormat類把MapReduce產生的結果集導入到數據庫表中。
2、由於0.20版本對DBInputFormat和DBOutputFormat支持不是很好,該例用了0.19版本來說明這兩個類的用法。
至少在我的 0.20.203 中的org.apache.hadoop.mapreduce.lib 下是沒見到 db 包,所以本文也是以老版的 API 來為例說明的。
3、運行MapReduce時候報錯:java.io.IOException: com.mysql.jdbc.Driver,一般是由於程序找不到mysql驅動包。解決方法是讓每個tasktracker運行MapReduce程序時都可以找到該驅動包。
添加包有兩種方式:
(1)在每個節點下的${HADOOP_HOME}/lib下添加該包。重啟集群,一般是比較原始的方法。
(2)a)把包傳到集群上: hadoop fs -put mysql-connector-java-5.1.0- bin.jar /hdfsPath/
b)在mr程序提交job前,添加語句:DistributedCache.addFileToClassPath(new Path(“/hdfsPath/mysql- connector-java- 5.1.0-bin.jar”), conf);
(3)雖然API用的是0.19的,但是使用0.20的API一樣可用,只是會提示方法已過時而已。
4、測試數據:
- CREATE TABLE `t` (
- `id` int DEFAULT NULL,
- `name` varchar(10) DEFAULT NULL
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- CREATE TABLE `t2` (
- `id` int DEFAULT NULL,
- `name` varchar(10) DEFAULT NULL
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- insert into t values (1,"june"),(2,"decli"),(3,"hello"),
- (4,"june"),(5,"decli"),(6,"hello"),(7,"june"),
- (8,"decli"),(9,"hello"),(10,"june"),
- (11,"june"),(12,"decli"),(13,"hello");
5、代碼:
- package mysql2mr;
- import java.io.DataInput;
- import java.io.DataOutput;
- import java.io.File;
- import java.io.IOException;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import mapr.EJob;
- import org.apache.hadoop.conf.Configuration;
- import org.apache.hadoop.filecache.DistributedCache;
- import org.apache.hadoop.fs.Path;
- import org.apache.hadoop.io.LongWritable;
- import org.apache.hadoop.io.Text;
- import org.apache.hadoop.io.Writable;
- import org.apache.hadoop.mapred.JobConf;
- import org.apache.hadoop.mapreduce.Job;
- import org.apache.hadoop.mapreduce.Mapper;
- import org.apache.hadoop.mapreduce.Reducer;
- import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
- import org.apache.hadoop.mapreduce.lib.db.DBInputFormat;
- import org.apache.hadoop.mapreduce.lib.db.DBOutputFormat;
- import org.apache.hadoop.mapreduce.lib.db.DBWritable;
- /**
- * Function: 測試 mr 與 mysql 的數據交互,此測試用例將一個表中的數據復制到另一張表中 實際當中,可能只需要從 mysql 讀,或者寫到
- * mysql 中。
- *
- * @author administrator
- *
- */
- public class Mysql2Mr {
- public static class StudentinfoRecord implements Writable, DBWritable {
- int id;
- String name;
- public StudentinfoRecord() {
- }
- public String toString() {
- return new String(this.id + " " + this.name);
- }
- @Override
- public void readFields(ResultSet result) throws SQLException {
- this.id = result.getInt(1);
- this.name = result.getString(2);
- }
- @Override
- public void write(PreparedStatement stmt) throws SQLException {
- stmt.setInt(1, this.id);
- stmt.setString(2, this.name);
- }
- @Override
- public void readFields(DataInput in) throws IOException {
- this.id = in.readInt();
- this.name = Text.readString(in);
- }
- @Override
- public void write(DataOutput out) throws IOException {
- out.writeInt(this.id);
- Text.writeString(out, this.name);
- }
- }
- // 記住此處是靜態內部類,要不然你自己實現無參構造器,或者等着拋異常:
- // Caused by: java.lang.NoSuchMethodException: DBInputMapper.<init>()
- // http://stackoverflow.com/questions/7154125/custom-mapreduce-input-format-cant-find-constructor
- // 網上腦殘式的轉帖,沒見到一個寫對的。。。
- public static class DBInputMapper extends
- Mapper<LongWritable, StudentinfoRecord, LongWritable, Text> {
- @Override
- public void map(LongWritable key, StudentinfoRecord value,
- Context context) throws IOException, InterruptedException {
- context.write(new LongWritable(value.id), new Text(value.toString()));
- }
- }
- public static class MyReducer extends Reducer<LongWritable, Text, StudentinfoRecord, Text> {
- @Override
- public void reduce(LongWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
- String[] splits = values.iterator().next().toString().split(" ");
- StudentinfoRecord r = new StudentinfoRecord();
- r.id = Integer.parseInt(splits[0]);
- r.name = splits[1];
- context.write(r, new Text(r.name));
- }
- }
- @SuppressWarnings("deprecation")
- public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
- File jarfile = EJob.createTempJar("bin");
- EJob.addClasspath("usr/hadoop/conf");
- ClassLoader classLoader = EJob.getClassLoader();
- Thread.currentThread().setContextClassLoader(classLoader);
- Configuration conf = new Configuration();
- // 這句話很關鍵
- conf.set("mapred.job.tracker", "172.30.1.245:9001");
- DistributedCache.addFileToClassPath(new Path(
- "hdfs://172.30.1.245:9000/user/hadoop/jar/mysql-connector-java-5.1.6-bin.jar"), conf);
- DBConfiguration.configureDB(conf, "com.mysql.jdbc.Driver", "jdbc:mysql://172.30.1.245:3306/sqooptest", "sqoop", "sqoop");
- Job job = new Job(conf, "Mysql2Mr");
- // job.setJarByClass(Mysql2Mr.class);
- ((JobConf)job.getConfiguration()).setJar(jarfile.toString());
- job.setMapOutputKeyClass(LongWritable.class);
- job.setMapOutputValueClass(Text.class);
- job.setMapperClass(DBInputMapper.class);
- job.setReducerClass(MyReducer.class);
- job.setOutputKeyClass(LongWritable.class);
- job.setOutputValueClass(Text.class);
- job.setOutputFormatClass(DBOutputFormat.class);
- job.setInputFormatClass(DBInputFormat.class);
- String[] fields = {"id","name"};
- // 從 t 表讀數據
- DBInputFormat.setInput(job, StudentinfoRecord.class, "t", null, "id", fields);
- // mapreduce 將數據輸出到 t2 表
- DBOutputFormat.setOutput(job, "t2", "id", "name");
- System.exit(job.waitForCompletion(true)? 0:1);
- }
- }
6、結果:
執行兩次后,你可以看到mysql結果:
- mysql> select * from t2;
- +------+-------+
- | id | name |
- +------+-------+
- | 1 | june |
- | 2 | decli |
- | 3 | hello |
- | 4 | june |
- | 5 | decli |
- | 6 | hello |
- | 7 | june |
- | 8 | decli |
- | 9 | hello |
- | 10 | june |
- | 11 | june |
- | 12 | decli |
- | 13 | hello |
- | 1 | june |
- | 2 | decli |
- | 3 | hello |
- | 4 | june |
- | 5 | decli |
- | 6 | hello |
- | 7 | june |
- | 8 | decli |
- | 9 | hello |
- | 10 | june |
- | 11 | june |
- | 12 | decli |
- | 13 | hello |
- +------+-------+
- 26 rows in set (0.00 sec)
- mysql>