有时候我们在项目中会遇到输入结果集很大,但是输出结果很小,比如一些 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、测试数据:

  1. CREATE TABLE `t` (
  2. `id` int DEFAULT NULL,
  3. `name` varchar(10) DEFAULT NULL
  4. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  5. CREATE TABLE `t2` (
  6. `id` int DEFAULT NULL,
  7. `name` varchar(10) DEFAULT NULL
  8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  9. insert into t values (1,"june"),(2,"decli"),(3,"hello"),
  10. (4,"june"),(5,"decli"),(6,"hello"),(7,"june"),
  11. (8,"decli"),(9,"hello"),(10,"june"),
  12. (11,"june"),(12,"decli"),(13,"hello");

5、代码:

  1. package mysql2mr;
  2. import java.io.DataInput;
  3. import java.io.DataOutput;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.SQLException;
  9. import mapr.EJob;
  10. import org.apache.hadoop.conf.Configuration;
  11. import org.apache.hadoop.filecache.DistributedCache;
  12. import org.apache.hadoop.fs.Path;
  13. import org.apache.hadoop.io.LongWritable;
  14. import org.apache.hadoop.io.Text;
  15. import org.apache.hadoop.io.Writable;
  16. import org.apache.hadoop.mapred.JobConf;
  17. import org.apache.hadoop.mapreduce.Job;
  18. import org.apache.hadoop.mapreduce.Mapper;
  19. import org.apache.hadoop.mapreduce.Reducer;
  20. import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
  21. import org.apache.hadoop.mapreduce.lib.db.DBInputFormat;
  22. import org.apache.hadoop.mapreduce.lib.db.DBOutputFormat;
  23. import org.apache.hadoop.mapreduce.lib.db.DBWritable;
  24. /**
  25. * Function: 测试 mr 与 mysql 的数据交互,此测试用例将一个表中的数据复制到另一张表中 实际当中,可能只需要从 mysql 读,或者写到
  26. * mysql 中。
  27. *
  28. * @author administrator
  29. *
  30. */
  31. public class Mysql2Mr {
  32. public static class StudentinfoRecord implements Writable, DBWritable {
  33. int id;
  34. String name;
  35. public StudentinfoRecord() {
  36. }
  37. public String toString() {
  38. return new String(this.id + " " + this.name);
  39. }
  40. @Override
  41. public void readFields(ResultSet result) throws SQLException {
  42. this.id = result.getInt(1);
  43. this.name = result.getString(2);
  44. }
  45. @Override
  46. public void write(PreparedStatement stmt) throws SQLException {
  47. stmt.setInt(1, this.id);
  48. stmt.setString(2, this.name);
  49. }
  50. @Override
  51. public void readFields(DataInput in) throws IOException {
  52. this.id = in.readInt();
  53. this.name = Text.readString(in);
  54. }
  55. @Override
  56. public void write(DataOutput out) throws IOException {
  57. out.writeInt(this.id);
  58. Text.writeString(out, this.name);
  59. }
  60. }
  61. // 记住此处是静态内部类,要不然你自己实现无参构造器,或者等着抛异常:
  62. // Caused by: java.lang.NoSuchMethodException: DBInputMapper.<init>()
  63. // http://stackoverflow.com/questions/7154125/custom-mapreduce-input-format-cant-find-constructor
  64. // 网上脑残式的转帖,没见到一个写对的。。。
  65. public static class DBInputMapper extends
  66. Mapper<LongWritable, StudentinfoRecord, LongWritable, Text> {
  67. @Override
  68. public void map(LongWritable key, StudentinfoRecord value,
  69. Context context) throws IOException, InterruptedException {
  70. context.write(new LongWritable(value.id), new Text(value.toString()));
  71. }
  72. }
  73. public static class MyReducer extends Reducer<LongWritable, Text, StudentinfoRecord, Text> {
  74. @Override
  75. public void reduce(LongWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
  76. String[] splits = values.iterator().next().toString().split(" ");
  77. StudentinfoRecord r = new StudentinfoRecord();
  78. r.id = Integer.parseInt(splits[0]);
  79. r.name = splits[1];
  80. context.write(r, new Text(r.name));
  81. }
  82. }
  83. @SuppressWarnings("deprecation")
  84. public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
  85. File jarfile = EJob.createTempJar("bin");
  86. EJob.addClasspath("usr/hadoop/conf");
  87. ClassLoader classLoader = EJob.getClassLoader();
  88. Thread.currentThread().setContextClassLoader(classLoader);
  89. Configuration conf = new Configuration();
  90. // 这句话很关键
  91. conf.set("mapred.job.tracker", "172.30.1.245:9001");
  92. DistributedCache.addFileToClassPath(new Path(
  93. "hdfs://172.30.1.245:9000/user/hadoop/jar/mysql-connector-java-5.1.6-bin.jar"), conf);
  94. DBConfiguration.configureDB(conf, "com.mysql.jdbc.Driver", "jdbc:mysql://172.30.1.245:3306/sqooptest", "sqoop", "sqoop");
  95. Job job = new  Job(conf, "Mysql2Mr");
  96. //      job.setJarByClass(Mysql2Mr.class);
  97. ((JobConf)job.getConfiguration()).setJar(jarfile.toString());
  98. job.setMapOutputKeyClass(LongWritable.class);
  99. job.setMapOutputValueClass(Text.class);
  100. job.setMapperClass(DBInputMapper.class);
  101. job.setReducerClass(MyReducer.class);
  102. job.setOutputKeyClass(LongWritable.class);
  103. job.setOutputValueClass(Text.class);
  104. job.setOutputFormatClass(DBOutputFormat.class);
  105. job.setInputFormatClass(DBInputFormat.class);
  106. String[] fields = {"id","name"};
  107. // 从 t 表读数据
  108. DBInputFormat.setInput(job, StudentinfoRecord.class, "t", null, "id", fields);
  109. // mapreduce 将数据输出到 t2 表
  110. DBOutputFormat.setOutput(job, "t2", "id", "name");
  111. System.exit(job.waitForCompletion(true)? 0:1);
  112. }
  113. }

6、结果:

执行两次后,你可以看到mysql结果:

  1. mysql> select * from t2;
  2. +------+-------+
  3. | id   | name  |
  4. +------+-------+
  5. |    1 | june  |
  6. |    2 | decli |
  7. |    3 | hello |
  8. |    4 | june  |
  9. |    5 | decli |
  10. |    6 | hello |
  11. |    7 | june  |
  12. |    8 | decli |
  13. |    9 | hello |
  14. |   10 | june  |
  15. |   11 | june  |
  16. |   12 | decli |
  17. |   13 | hello |
  18. |    1 | june  |
  19. |    2 | decli |
  20. |    3 | hello |
  21. |    4 | june  |
  22. |    5 | decli |
  23. |    6 | hello |
  24. |    7 | june  |
  25. |    8 | decli |
  26. |    9 | hello |
  27. |   10 | june  |
  28. |   11 | june  |
  29. |   12 | decli |
  30. |   13 | hello |
  31. +------+-------+
  32. 26 rows in set (0.00 sec)
  33. mysql>

Hadoop 中利用 mapreduce 读写 mysql 数据的更多相关文章

  1. MATLAB中文件的读写和数据的导入导出

    http://blog.163.com/tawney_daylily/blog/static/13614643620111117853933/ 在编写一个程序时,经常需要从外部读入数据,或者将程序运行 ...

  2. Hadoop生态圈-使用MapReduce处理HBase数据

    Hadoop生态圈-使用MapReduce处理HBase数据 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.对HBase表中数据进行单词统计(TableInputFormat) ...

  3. 使用MapReduce将mysql数据导入HDFS

    package com.zhen.mysqlToHDFS; import java.io.DataInput; import java.io.DataOutput; import java.io.IO ...

  4. 一脸懵逼学习Hadoop中的MapReduce程序中自定义分组的实现

    1:首先搞好实体类对象: write 是把每个对象序列化到输出流,readFields是把输入流字节反序列化,实现WritableComparable,Java值对象的比较:一般需要重写toStrin ...

  5. android开发中 解决服务器端解析MySql数据时中文显示乱码的情况

    首先,还是确认自己MySql账户和密码 1.示例  账户:root   密码:123456   有三个字段   分别是_id  .username(插入有中文数据).password 1)首先我们知道 ...

  6. Hadoop 中的 (side data) 边数据

    一.用途 边数据是作业所需的额外的只读数据,通常用来辅助主数据集: 二.方法 1.利用Configuration类来配置,利用setter()和getter()可方便的使用,方便存储一些基本的类型: ...

  7. 利用innodb_force_recovery修复MySQL数据页损坏

    现象:启动MySQL服务时报1067错误,服务无法启动. 查看xxx.err错误日志发现有数据页损坏信息: InnoDB: Database page corruption on disk or a  ...

  8. SQLServer中利用NTILE函数对数据进行分组的一点使用

    本文出处:http://www.cnblogs.com/wy123/p/6908377.html NTILE函数可以按照指定的排序规则,对数据按照指定的组数(M个对象,按照某种排序分N个组)进行分组, ...

  9. R中利用SQL语言读取数据框(sqldf库的使用)

    熟悉MySQL的朋友可以使用sqldf来操作数据框 # 引入sqldf库(sqldf) library(sqldf) # 释放RMySQL库的加载(针对sqldf报错) #detach("p ...

随机推荐

  1. 【分享】标准springMVC+mybatis项目maven搭建最精简教程

    文章由来:公司有个实习同学需要做毕业设计,不会搭建环境,我就代劳了,顺便分享给刚入门的小伙伴,我是自学的JAVA,所以我懂的.... (大图直接观看显示很模糊,请在图片上点击右键然后在新窗口打开看) ...

  2. 多线程爬坑之路-Thread和Runable源码解析之基本方法的运用实例

    前面的文章:多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类) 多线程爬坑之路-Thread和Runable源码解析 前面 ...

  3. javaScript中的小细节-script标签中的预解析

    首先介绍预解析,虽然预解析字面意思很好理解,但是却是出坑出的最多的地方,也是bug经常会有的地方,利用好预解析的特性可以解决很多问题,并且提高代码的质量及数量,浏览器在解析代码前会把变量的声明和函数( ...

  4. RMS:不能对生产服务器使用测试清单

    问题说明:在使用office软件RMS加密时报:不能对生产服务器使用测试清单,或者使用 rmsbulk.exe进行RMS加密时,报不能连接到RMS服务器. 解决办法: 请到https://suppor ...

  5. linux启动SSH及开机自动启动

    本文地址 分享提纲: 1.查看是否启动 2. 设置自动启动 1.[查看是否启动] 启动SSH服务 “/etc/init.d/sshd start”.然后用netstat -antulp | grep ...

  6. 【repost】JS错误类型的学习

    SyntaxError是解析代码时发生的语法错误 // 变量名错误  var 1a;  // 缺少括号  console.log 'hello'); (2)ReferenceError Referen ...

  7. Android(2)—Mono For Android App版本自动更新

    0.前言 公司Android查询的项目已经开始,整体采用Java后台+App前台来实现,由于项目小,App这块就我一个人开发,首先需要研究的是:Android版本的更新升级问题:本人经过近一周的学习整 ...

  8. 搞了我一下午竟然是web.config少写了一个点

    Safari手机版居然有个这么愚蠢的bug,浪费了我整个下午,使尽浑身解数,国内国外网站搜索解决方案,每一行代码读了又想想了又读如此不知道多少遍,想破脑袋也想不通到底哪里出了问题,结果竟然是web.c ...

  9. ucos实时操作系统学习笔记——任务间通信(消息)

    ucos另一种任务间通信的机制是消息(mbox),个人感觉是它是queue中只有一个信息的特殊情况,从代码中可以很清楚的看到,因为之前有关于queue的学习笔记,所以一并讲一下mbox.为什么有了qu ...

  10. Ubuntu部署python3.5的开发和运行环境

    Ubuntu部署python3.5的开发和运行环境 1 概述 由于最近项目全部由python2.x转向 python3.x(使用目前最新的 python3.5.1) ,之前的云主机的的默认python ...