有时候我们在项目中会遇到输入结果集很大,但是输出结果很小,比如一些 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. 关于如何提高Web服务端并发效率的异步编程技术

    最近我研究技术的一个重点是java的多线程开发,在我早期学习java的时候,很多书上把java的多线程开发标榜为简单易用,这个简单易用是以C语言作为参照的,不过我也没有使用过C语言开发过多线程,我只知 ...

  2. Security Policy:行级安全(Row-Level Security)

    行级安全RLS(Row-Level Security)是在数据行级别上控制用户的访问,控制用户只能访问数据库表的特定数据行.断言是逻辑表达式,在SQL Server 2016中,RLS是基于安全断言( ...

  3. 【SSM框架】Spring + Springmvc + Mybatis 基本框架搭建集成教程

    本文将讲解SSM框架的基本搭建集成,并有一个简单demo案例 说明:1.本文暂未使用maven集成,jar包需要手动导入. 2.本文为基础教程,大神切勿见笑. 3.如果对您学习有帮助,欢迎各种转载,注 ...

  4. HTTP常用状态码分析

    不管是面试还是工作中,经常会碰到需要通过HTTP状态码去判断问题的情况,比如对于后台RD,给到前端FE的一个接口,出现502或者504 error错误,FE就会说接口存在问题,如果没有知识储备,那就只 ...

  5. Xamarin+Prism开发详解三:Visual studio 2017 RC初体验

    Visual studio 2017 RC出来一段时间了,最近有时间就想安装试试,随带分享一下安装使用体验. 1,卸载visual studio 2015 虽然可以同时安装visual studio ...

  6. B样条基函数的定义和性质

    定义:令U={u0,u1,…,um}是一个单调不减的实数序列,即ui≤ui+1,i=0,1,…,m-1.其中,ui称为节点,U称为节点矢量,用Ni,p(u)表示第i个p次(p+1阶)B样条基函数,其定 ...

  7. 深入理解 JavaScript,以及 Linux 下的开发调试工具

    前言 JavaScript 是我接触到的第二门编程语言,第一门是 C 语言.然后才是 C++.Java 还有其它一些什么.所以我对 JavaScript 是非常有感情的,毕竟使用它有十多年了.早就想写 ...

  8. cocos2dx调用浏览器打开网址

    安卓端cocos2dx/platform/android路径下CCApplication.h: virtual void openURL(const char* pszUrl); CCApplicat ...

  9. Node.js学习笔记——Node.js开发Web后台服务

    一.简介 Node.js 是一个基于Google Chrome V8 引擎的 JavaScript 运行环境.Node.js 使用了一个事件驱动.非阻塞式 I/O 的模型,使其轻量又高效.Node.j ...

  10. SQL SERVER导入数据到ORACLE的方法总结

    我们偶尔会有将数据从SQL SERVER导入到ORACLE当中的这种需求,那么这种跨数据库导数有那些方法呢?这些方法又有那些利弊呢? 下面比较肤浅的总结了一些可行的方法. 1:生成SQL脚本然后去OR ...