有时候我们在项目中会遇到输入结果集很大,但是输出结果很小,比如一些 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. TODO:macOS上ThinkPHP5和Semantic-UI集成

    TODO:macOS上ThinkPHP5和Semantic-UI集成 1. 全局安装 (on OSX via homebrew)Composer 是 homebrew-php 项目的一部分 2. 把X ...

  2. 如何快速优化手游性能问题?从UGUI优化说起

    WeTest 导读   本文作者从自身多年的Unity项目UI开发及优化的经验出发,从UGUI,CPU,GPU以及unity特有资源等几个维度,介绍了unity手游性能优化的一些方法.   在之前的文 ...

  3. css3圆形百分比进度条的实现原理

    原文地址:css3圆形百分比进度条的实现原理 今天早上起来在查看jquery插件机制的时候,一不小心点进了css3圆形百分比进度条的相关文章,于是一发不可收拾,开始折腾了... 关于圆形圈的实现,想必 ...

  4. EC笔记:第4部分:22、所有成员都应该是private的

    EC笔记:第4部分:22.所有成员都应该是private的 更简单的访问 用户不用记得什么时候该带上括号,什么时候不用带上括号(因为很确定的就要带上括号) 访问限制 对于public的成员变量,我们可 ...

  5. IteratorPattern(迭代子模式)

    /** * 迭代子模式 * @author TMAC-J * 聚合:某一类对象的集合 * 迭代:行为方式,用来处理聚合 * 是一种行为模式,用于将聚合本身和操作聚合的行为分离 * Java中的COLL ...

  6. HTML5 Page Visibility

    什么是 Page Visibility ? Page Visibility 即页面可见性,通过 visibilityState 的值检测页面当前是否可见.当一个网站是可见或点击选中的状态时 Page ...

  7. Cesium简介以及离线部署运行

    Cesium简介 cesium是国外一个基于JavaScript编写的使用WebGL的地图引擎,一款开源3DGIS的js库.cesium支持3D,2D,2.5D形式的地图展示,可以自行绘制图形,高亮区 ...

  8. BPM协同平台解决方案分享

    一.需求分析 企业信息化的过程都是从单纯解决一个业务功能问题,到解决企业内部业务流程问题,再扩展到解决不同业务流程的关联互动问题, 核心是业务的集成和业务的协同,需要有一个统一的业务协同平台. 国内的 ...

  9. ReactiveCocoa代码实践之-UI组件的RAC信号操作

    上一节是自己对网络层的一些重构,本节是自己一些代码小实践做出的一些demo程序,基本涵盖大多数UI控件操作. 一.用UISlider实现调色板 假设我们现在做一个demo,上面有一个View用来展示颜 ...

  10. TFS 2015 敏捷开发实践 – 看板的使用

    看板在现代应用开发过程中使用非常广泛,不管是使用传统的瀑布式开发还是敏捷开发,都可以使用看板管理.因为看板拥有简单的管理方法,直观的显示方式,所以很多软件开发团队选择使用看板进行软件开发管理.本文不在 ...