Hadoop 中利用 mapreduce 读写 mysql 数据
有时候我们在项目中会遇到输入结果集很大,但是输出结果很小,比如一些 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、测试数据:
- CREATE TABLE `t` (
- `id` int DEFAULT NULL,
- `name` varchar(10) DEFAULT NULL
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- CREATE TABLE `t2` (
- `id` int DEFAULT NULL,
- `name` varchar(10) DEFAULT NULL
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- insert into t values (1,"june"),(2,"decli"),(3,"hello"),
- (4,"june"),(5,"decli"),(6,"hello"),(7,"june"),
- (8,"decli"),(9,"hello"),(10,"june"),
- (11,"june"),(12,"decli"),(13,"hello");
5、代码:
- package mysql2mr;
- import java.io.DataInput;
- import java.io.DataOutput;
- import java.io.File;
- import java.io.IOException;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import mapr.EJob;
- import org.apache.hadoop.conf.Configuration;
- import org.apache.hadoop.filecache.DistributedCache;
- import org.apache.hadoop.fs.Path;
- import org.apache.hadoop.io.LongWritable;
- import org.apache.hadoop.io.Text;
- import org.apache.hadoop.io.Writable;
- import org.apache.hadoop.mapred.JobConf;
- import org.apache.hadoop.mapreduce.Job;
- import org.apache.hadoop.mapreduce.Mapper;
- import org.apache.hadoop.mapreduce.Reducer;
- import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
- import org.apache.hadoop.mapreduce.lib.db.DBInputFormat;
- import org.apache.hadoop.mapreduce.lib.db.DBOutputFormat;
- import org.apache.hadoop.mapreduce.lib.db.DBWritable;
- /**
- * Function: 测试 mr 与 mysql 的数据交互,此测试用例将一个表中的数据复制到另一张表中 实际当中,可能只需要从 mysql 读,或者写到
- * mysql 中。
- *
- * @author administrator
- *
- */
- public class Mysql2Mr {
- public static class StudentinfoRecord implements Writable, DBWritable {
- int id;
- String name;
- public StudentinfoRecord() {
- }
- public String toString() {
- return new String(this.id + " " + this.name);
- }
- @Override
- public void readFields(ResultSet result) throws SQLException {
- this.id = result.getInt(1);
- this.name = result.getString(2);
- }
- @Override
- public void write(PreparedStatement stmt) throws SQLException {
- stmt.setInt(1, this.id);
- stmt.setString(2, this.name);
- }
- @Override
- public void readFields(DataInput in) throws IOException {
- this.id = in.readInt();
- this.name = Text.readString(in);
- }
- @Override
- public void write(DataOutput out) throws IOException {
- out.writeInt(this.id);
- Text.writeString(out, this.name);
- }
- }
- // 记住此处是静态内部类,要不然你自己实现无参构造器,或者等着抛异常:
- // Caused by: java.lang.NoSuchMethodException: DBInputMapper.<init>()
- // http://stackoverflow.com/questions/7154125/custom-mapreduce-input-format-cant-find-constructor
- // 网上脑残式的转帖,没见到一个写对的。。。
- public static class DBInputMapper extends
- Mapper<LongWritable, StudentinfoRecord, LongWritable, Text> {
- @Override
- public void map(LongWritable key, StudentinfoRecord value,
- Context context) throws IOException, InterruptedException {
- context.write(new LongWritable(value.id), new Text(value.toString()));
- }
- }
- public static class MyReducer extends Reducer<LongWritable, Text, StudentinfoRecord, Text> {
- @Override
- public void reduce(LongWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
- String[] splits = values.iterator().next().toString().split(" ");
- StudentinfoRecord r = new StudentinfoRecord();
- r.id = Integer.parseInt(splits[0]);
- r.name = splits[1];
- context.write(r, new Text(r.name));
- }
- }
- @SuppressWarnings("deprecation")
- public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
- File jarfile = EJob.createTempJar("bin");
- EJob.addClasspath("usr/hadoop/conf");
- ClassLoader classLoader = EJob.getClassLoader();
- Thread.currentThread().setContextClassLoader(classLoader);
- Configuration conf = new Configuration();
- // 这句话很关键
- conf.set("mapred.job.tracker", "172.30.1.245:9001");
- DistributedCache.addFileToClassPath(new Path(
- "hdfs://172.30.1.245:9000/user/hadoop/jar/mysql-connector-java-5.1.6-bin.jar"), conf);
- DBConfiguration.configureDB(conf, "com.mysql.jdbc.Driver", "jdbc:mysql://172.30.1.245:3306/sqooptest", "sqoop", "sqoop");
- Job job = new Job(conf, "Mysql2Mr");
- // job.setJarByClass(Mysql2Mr.class);
- ((JobConf)job.getConfiguration()).setJar(jarfile.toString());
- job.setMapOutputKeyClass(LongWritable.class);
- job.setMapOutputValueClass(Text.class);
- job.setMapperClass(DBInputMapper.class);
- job.setReducerClass(MyReducer.class);
- job.setOutputKeyClass(LongWritable.class);
- job.setOutputValueClass(Text.class);
- job.setOutputFormatClass(DBOutputFormat.class);
- job.setInputFormatClass(DBInputFormat.class);
- String[] fields = {"id","name"};
- // 从 t 表读数据
- DBInputFormat.setInput(job, StudentinfoRecord.class, "t", null, "id", fields);
- // mapreduce 将数据输出到 t2 表
- DBOutputFormat.setOutput(job, "t2", "id", "name");
- System.exit(job.waitForCompletion(true)? 0:1);
- }
- }
6、结果:
执行两次后,你可以看到mysql结果:
- mysql> select * from t2;
- +------+-------+
- | id | name |
- +------+-------+
- | 1 | june |
- | 2 | decli |
- | 3 | hello |
- | 4 | june |
- | 5 | decli |
- | 6 | hello |
- | 7 | june |
- | 8 | decli |
- | 9 | hello |
- | 10 | june |
- | 11 | june |
- | 12 | decli |
- | 13 | hello |
- | 1 | june |
- | 2 | decli |
- | 3 | hello |
- | 4 | june |
- | 5 | decli |
- | 6 | hello |
- | 7 | june |
- | 8 | decli |
- | 9 | hello |
- | 10 | june |
- | 11 | june |
- | 12 | decli |
- | 13 | hello |
- +------+-------+
- 26 rows in set (0.00 sec)
- mysql>
Hadoop 中利用 mapreduce 读写 mysql 数据的更多相关文章
- MATLAB中文件的读写和数据的导入导出
http://blog.163.com/tawney_daylily/blog/static/13614643620111117853933/ 在编写一个程序时,经常需要从外部读入数据,或者将程序运行 ...
- Hadoop生态圈-使用MapReduce处理HBase数据
Hadoop生态圈-使用MapReduce处理HBase数据 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.对HBase表中数据进行单词统计(TableInputFormat) ...
- 使用MapReduce将mysql数据导入HDFS
package com.zhen.mysqlToHDFS; import java.io.DataInput; import java.io.DataOutput; import java.io.IO ...
- 一脸懵逼学习Hadoop中的MapReduce程序中自定义分组的实现
1:首先搞好实体类对象: write 是把每个对象序列化到输出流,readFields是把输入流字节反序列化,实现WritableComparable,Java值对象的比较:一般需要重写toStrin ...
- android开发中 解决服务器端解析MySql数据时中文显示乱码的情况
首先,还是确认自己MySql账户和密码 1.示例 账户:root 密码:123456 有三个字段 分别是_id .username(插入有中文数据).password 1)首先我们知道 ...
- Hadoop 中的 (side data) 边数据
一.用途 边数据是作业所需的额外的只读数据,通常用来辅助主数据集: 二.方法 1.利用Configuration类来配置,利用setter()和getter()可方便的使用,方便存储一些基本的类型: ...
- 利用innodb_force_recovery修复MySQL数据页损坏
现象:启动MySQL服务时报1067错误,服务无法启动. 查看xxx.err错误日志发现有数据页损坏信息: InnoDB: Database page corruption on disk or a ...
- SQLServer中利用NTILE函数对数据进行分组的一点使用
本文出处:http://www.cnblogs.com/wy123/p/6908377.html NTILE函数可以按照指定的排序规则,对数据按照指定的组数(M个对象,按照某种排序分N个组)进行分组, ...
- R中利用SQL语言读取数据框(sqldf库的使用)
熟悉MySQL的朋友可以使用sqldf来操作数据框 # 引入sqldf库(sqldf) library(sqldf) # 释放RMySQL库的加载(针对sqldf报错) #detach("p ...
随机推荐
- 利用snowfall.jquery.js实现爱心满屏飞
小颖在上一篇一步一步教你用CSS画爱心中已经分享一种画爱心的方法,这次再分享一种方法用css画爱心,并利用snowfall.jquery.js实现爱心满屏飞的效果. 第一步: 利用伪元素before和 ...
- Minor【 PHP框架】1.简介
1.1 Minor是什么 Minor是一个简单但是优秀的符合PSR4的PHP框架,It just did what a framework should do. 只做一个框架应该做的,简单而又强大! ...
- html5标签canvas函数drawImage使用方法
html5中标签canvas,函数drawImage(): 使用drawImage()方法绘制图像.绘图环境提供了该方法的三个不同版本.参数传递三种形式: drawImage(image,x,y):在 ...
- 23种设计模式--责任链模式-Chain of Responsibility Pattern
一.责任链模式的介绍 责任链模式用简单点的话来说,将责任一步一步传下去,这就是责任,想到这个我们可以相当击鼓传花,这个是为了方便记忆,另外就是我们在项目中经常用到的审批流程等这一类的场景时我们就可以考 ...
- 【原创分享·微信支付】C# MVC 微信支付教程系列之现金红包
微信支付教程系列之现金红包 最近最弄这个微信支付的功能,然后扫码.公众号支付,这些都做了,闲着无聊,就看了看微信支付的其他功能,发现还有一个叫“现金红包”的玩意,想 ...
- [C#] C# 知识回顾 - 特性 Attribute
C# 知识回顾 - 特性 Attribute [博主]反骨仔 [原文地址]http://www.cnblogs.com/liqingwen/p/5911289.html 目录 特性简介 使用特性 特性 ...
- 解决VS2008在win7找不到输入序列号的地方
1.VS2008在Windows7 打开维护界面看不到可以输序列号的地方. 因为微软把他隐藏了. 2.我们可以借用工具把他显示出来 下载地址:http://www.zlsoft.com/techbbs ...
- [算法]——归并排序(Merge Sort)
归并排序(Merge Sort)与快速排序思想类似:将待排序数据分成两部分,继续将两个子部分进行递归的归并排序:然后将已经有序的两个子部分进行合并,最终完成排序.其时间复杂度与快速排序均为O(nlog ...
- SQL Server的AlwaysOn错误19456和41158
SQL Server的AlwaysOn错误19456和41158 最近在公司搞异地数据库容灾,使用AlwaysOn的异地节点进行数据同步,在搭建的过程中遇到了一些问题 软件版本 SQL Server2 ...
- 在树莓派Raspbian下安装支持Hard Float的.NET环境
[题外话] 最近入了个树莓派玩,系统装的官方推荐的Hard Float的Raspbian,由于衍生自Debian,所以Mono什么的非常好装.但是官方源中的Mono在Hard Float的Raspbi ...