有时候我们在项目中会遇到输入结果集很大,但是输出结果很小,比如一些 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. 从Membership 到 .NET4.5 之 ASP.NET Identity

    我们前面已经讨论过了如何在一个网站中集成最基本的Membership功能,然后深入学习了Membership的架构设计.正所谓从实践从来,到实践从去,在我们把Membership的结构吃透之后,我们要 ...

  2. LeetCode-5LongestPalindromicSubstring(C#)

    # 题目 5. Longest Palindromic Substring Given a string S, find the longest palindromic substring in S. ...

  3. 如何在nuget上传自己的包+搭建自己公司的NuGet服务器(新方法)

    运维相关:http://www.cnblogs.com/dunitian/p/4822808.html#iis 先注册一个nuget账号https://www.nuget.org/ 下载并安装一下Nu ...

  4. HTML 事件(四) 模拟事件操作

    本篇主要介绍HTML DOM中事件的模拟操作. 其他事件文章 1. HTML 事件(一) 事件的介绍 2. HTML 事件(二) 事件的注册与注销 3. HTML 事件(三) 事件流与事件委托 4.  ...

  5. J a v a 的“多重继承”

    接口只是比抽象类“更纯”的一种形式.它的用途并不止那些.由于接口根本没有具体的实施细节——也就是说,没有与存储空间与“接口”关联在一起——所以没有任何办法可以防止多个接口合并到一起.这一点是至关重要的 ...

  6. Autofac - MVC/WebApi中的应用

    Autofac前面写了那么多篇, 其实就是为了今天这一篇, Autofac在MVC和WebApi中的应用. 一.目录结构 先看一下我的目录结构吧, 搭了个非常简单的架构, IOC(web), IBLL ...

  7. 微信小程序的机会在于重新理解群组与二维码

    历时一年,唯一一个尚未发布就获得Pony Ma与Allen Zhang站台的产品:微信小程序,将于2017年1月9日正式上线了.我很期待.唯一要警惕的是:防止长考出臭棋. 在上线前夕,我对于如何借助小 ...

  8. 升级npm

    查看npm的所有版本 运行命令: npm view npm versions 命令运行后,会输出到目前为止npm的所有版本. [ '1.1.25', '1.1.70', '1.1.71', '1.2. ...

  9. Atitit 软件工程概览attilax总结

    Atitit 软件工程概览attilax总结 1.1. .2 软件工程的发展 进一步地,结合人类发展史和计算机世界演化史来考察软件工程的发展史. 表2 软件工程过程模型 表2将软件工程的主要过程模型做 ...

  10. 萌新笔记——linux下查看内存的使用情况

    windows上有各种软件可以进行"一键加速"之类的操作,释放掉一些内存(虽然我暂时不知道是怎么办到的,有待后续学习).而任务管理器也可以很方便地查看各进程使用的内存情况,如下图: ...