有时候我们在项目中会遇到输入结果集很大,但是输出结果很小,比如一些 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. 谈一下关于CQRS架构如何实现高性能

    CQRS架构简介 前不久,看到博客园一位园友写了一篇文章,其中的观点是,要想高性能,需要尽量:避开网络开销(IO),避开海量数据,避开资源争夺.对于这3点,我觉得很有道理.所以也想谈一下,CQRS架构 ...

  2. Visaul Studio 常用快捷键的动画演示

    从本篇文章开始,我将会陆续介绍提高 VS 开发效率的文章,欢迎大家补充~ 在进行代码开发的时候,我们往往会频繁的使用键盘.鼠标进行协作,但是切换使用两种工具会影响到我们的开发速度,如果所有的操作都可以 ...

  3. 【.net 深呼吸】跨应用程序域执行程序集

    应用程序域,你在网上可以查到它的定义,凡是概念性的东西,大伙儿只需要会搜索就行,内容看了就罢,不用去记忆,更不用去背,“名词解释”是大学考试里面最无聊最没水平的题型. 简单地说,应用程序域让你可以在一 ...

  4. 【接口开发】浅谈 SOAP Webserver 与 Restful Webserver 区别

    接口,强大,简单,交互,跨越平台 下面简单阐述这两大接口思想 一 REST: REST是一种架构风格,其核心是面向资源,REST专门针对网络应用设计和开发方式,以降低开发的复杂性,提高系统的可伸缩性. ...

  5. 使用python抓取婚恋网用户数据并用决策树生成自己择偶观

    最近在看<机器学习实战>的时候萌生了一个想法,自己去网上爬一些数据按照书上的方法处理一下,不仅可以加深自己对书本的理解,顺便还可以在github拉拉人气.刚好在看决策树这一章,书里面的理论 ...

  6. Oracle学习之路-- 案例分析实现行列转换的几种方式

    注:本文使用的数据库表为oracle自带scott用户下的emp,dept等表结构. 通过一个例子来说明行列转换: 需求:查询每个部门中各个职位的总工资 按我们最原始的思路可能会这么写:       ...

  7. 移动应用App测试与质量管理一

    测试工程师 基于Html的WebApp测试, 现在一些移动App混Html5 HTML5性能测试 兼容性 整理后的脑图 测试招聘 弱化大量技术考察 看重看问题的高度 看重潜力 测试经验 质量管理 专项 ...

  8. SharePoint 2013: A feature with ID has already been installed in this farm

    使用Visual Studio 2013创建一个可视web 部件,当右击项目选择"部署"时报错: "Error occurred in deployment step ' ...

  9. MySQL加密

    MySQL字段加密和解密 1.加密:aes_encrypt('admin','key') 解密:aes_decrypt(password,'key') 2.双向加密 通过密钥去加密,解密的时候的只有知 ...

  10. Struts2.5需要的最少jar文件

    以Struts2.5.2为例 从官网上下载“struts-2.5.2-min-lib.zip”,里面有7个jar文件: commons-fileupload-1.3.2.jarcommons-io-2 ...