应用场景:使用JavaHiveContext执行SQL之后,希望能得到其字段名及相应的值,但却出现"Caused by: java.io.NotSerializableException: org.apache.spark.sql.api.java.StructField"的错误,代码如下:

JavaSparkContext sc = new JavaSparkContext(conf);
JavaHiveContext sqlContext = new JavaHiveContext(sc);
JavaSchemaRDD schema = sqlContext.sql("select * from default.dual");
final StructField[] fields = schema.schema().getFields();
JavaRDD<String> result = schema.map(new Function<Row, String>() {
private static final long serialVersionUID = 1L;
@Override
public String call(Row row) throws Exception {
StringBuffer out = new StringBuffer();
for (int i = 0; i < row.length(); i++) {
out.append(fields[i].getName() + "->" + row.get(i) + ";");
}
return out.toString();
}
});
System.out.println(result.collect());

在spark官网上查找序列化方面的内容,看到可以通过注册的方式自定义类的序列化方式,故在conf上添加以下设置:

conf.registerKryoClasses(new Class[] { org.apache.spark.sql.api.java.StructField.class });

测试执行后,还是报相同的错误:java.io.NotSerializableException: org.apache.spark.sql.api.java.StructField,不知道为什么,如果有朋友知道,可在下面留言。

上述方法测不通后,又再网上寻求方法,此时看到了下面的这篇文章,内容摘录见下:http://www.cnblogs.com/zwCHAN/p/4305156.html

按照第一种方法,将依赖的变量StructField[]放到map内部定义,代码见下:

JavaSparkContext sc = new JavaSparkContext(conf);
JavaHiveContext sqlContext = new JavaHiveContext(sc);
JavaSchemaRDD schema = sqlContext.sql("select * from default.dual");
JavaRDD<String> result = schema.map(new Function<Row, String>() {
private static final long serialVersionUID = 1L;
@Override
public String call(Row row) throws Exception {
StructField[] fields = schema.schema().getFields();
StringBuffer out = new StringBuffer();
for (int i = 0; i < row.length(); i++) {
out.append(fields[i].getName() + "->" + row.get(i) + ";");
}
return out.toString();
}
});
System.out.println(result.collect());

  

测试通过,但考虑到每次map都需要从JavaSchemaRDD中获取一次schema信息,比较耗时,而在map中有只需要String类型的字段名就可以了,故在原有基础上对代码进行优化,见下:

JavaSparkContext sc = new JavaSparkContext(conf);
JavaHiveContext sqlContext = new JavaHiveContext(sc);
JavaSchemaRDD schema = sqlContext.sql("select * from default.dual");
StructField[] fields = schema.schema().getFields();
final String[] fieldsName = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
fieldsName[i] = fields[i].getName();
}
JavaRDD<String> result = schema.map(new Function<Row, String>() {
private static final long serialVersionUID = 1L;
@Override
public String call(Row row) throws Exception {
StringBuffer out = new StringBuffer();
for (int i = 0; i < row.length(); i++) {
out.append(fieldsName[i] + "->" + row.get(i) + ";");
}
return out.toString();
}
});
System.out.println(result.collect());

以下内容摘录自:http://www.cnblogs.com/zwCHAN/p/4305156.html

出现“org.apache.spark.SparkException: Task not serializable"这个错误,一般是因为在map、filter等的参数使用了外部的变量,但是这个变量不能序列化。特别是当引用了某个类(经常是当前类)的成员函数或变量时,会导致这个类的所有成员(整个类)都需要支持序列化。解决这个问题最常用的方法有:

  1. 如果可以,将依赖的变量放到map、filter等的参数内部定义。这样就可以使用不支持序列化的类;
  2. 如果可以,将依赖的变量独立放到一个小的class中,让这个class支持序列化;这样做可以减少网络传输量,提高效率;
  3. 如果可以,将被依赖的类中不能序列化的部分使用transient关键字修饰,告诉编译器它不需要序列化。
  4. 将引用的类做成可序列化的。
  5. 以下这两个没试过。。
  • Make the NotSerializable object as a static and create it once per machine.
  • Call rdd.forEachPartition and create the NotSerializable object in there like this:
==================

If you see this error:

org.apache.spark.SparkException: Job aborted due to stage failure: Task not serializable: java.io.NotSerializableException: ...

The above error can be triggered when you intialize a variable on the driver (master), but then try to use it on one of the workers. In that case, Spark Streaming will try to serialize the object to send it over to the worker, and fail if the object is not serializable. Consider the following code snippet:

NotSerializable notSerializable = new NotSerializable();
JavaRDD<String> rdd = sc.textFile("/tmp/myfile"); rdd.map(s -> notSerializable.doSomething(s)).collect();

This will trigger that error. Here are some ideas to fix this error:

  • Serializable the class
  • Declare the instance only within the lambda function passed in map.
  • Make the NotSerializable object as a static and create it once per machine.
  • Call rdd.forEachPartition and create the NotSerializable object in there like this:
rdd.forEachPartition(iter -> {
NotSerializable notSerializable = new NotSerializable(); // ...Now process iter
});

另外, stackoverflow上http://stackoverflow.com/questions/25914057/task-not-serializable-exception-while-running-apache-spark-job 这个答的也很简明易懂。

spark出现task不能序列化错误的解决方法的更多相关文章

  1. spark出现task不能序列化错误的解决方法 org.apache.spark.SparkException: Task not serializable

    import org.elasticsearch.cluster.routing.Murmur3HashFunction; import org.elasticsearch.common.math.M ...

  2. Linux出现Read-only file system错误的解决方法

    造成这个问题的解决办法大多数是由于非正常关机后导致文件系统受损引起的,在系统重新启动之后,受损分区就会被Linux自己主动挂载为仅仅读.解决办法是通过fsck来修复文件系统,然后重新启动就可以,下面是 ...

  3. Eclipse启动时发生An internal error occurred during: "Initializing Java Tooling".错误的解决方法

    问题描述: Eclipse启动时发生An internal error occurred during: "Initializing JavaTooling".错误的解决方法 解决 ...

  4. GCC-4.6.3编译linux2.6.32.12内核出现“重复的成员‘page’”错误的解决方法

    使用gcc4.6.3编译linux2.6.32.12内核出现错误如下: In file included from drivers/net/igbvf/ethtool.c:36:0: drivers/ ...

  5. Linux系统Vsftp 传文件出现 553 Could Not Create File错误的解决方法

    解决方法: 登录出现了这个错误提示:553 Could not create file SELinux设置如下 查看SELinux设置 [root@localhost ~]# getsebool -a ...

  6. [转]权限问题导致Nginx 403 Forbidden错误的解决方法

    权限问题导致Nginx 403 Forbidden错误的解决方法 投稿:junjie 字体:[增加 减小] 类型:转载 时间:2014-08-22 这篇文章主要介绍了权限问题导致Nginx 403 F ...

  7. ueditor上传大容量视频报http请求错误的解决方法

    故障现象: 当使用百度编辑器ueditor上传大容量视频或大容量图片的时候,编辑器报"http请求错误"的解决方法详解: 原因分析: 目前很多CMS整合了百度的ueditor编辑器 ...

  8. window10 安装出现the error code is 2503错误的解决方法

    window10 安装出现the error code is 2503错误的解决方法:  设置 C:\WINDOWS\TEMP的权限

  9. MyEclipse+Tomcat 启动时出现A configuration error occured during startup错误的解决方法

    MyEclipse+Tomcat 启动时出现A configuration error occured during startup错误的解决方法 分类: javaweb2013-06-03 14:4 ...

随机推荐

  1. (转)Shell分析服务器日志

    一.目录 转载链接:https://mp.weixin.qq.com/s/W1ekSiHgbGInqQ9HmZaJDA 自己的小网站跑在阿里云的ECS上面,偶尔也去分析分析自己网站服务器日志,看看网站 ...

  2. HTML学习-02

    1.本次学习主要是css和页面的跳转 <!DOCTYPE html> <html> <head> <meta charset="UTF-8" ...

  3. linux切换php版本

    1.查看php版本 find / -name .php 2.vim /etc/profile 3.加上export PATH=/usr/local/php5.6/bin:$PATH 4.source ...

  4. GCC 7.3.0版本编译http-parser-2.1问题

    http-paser是一个用c编写的http消息解析器,地址:https://github.com/nodejs/http-parser,目前版本2.9 今天用gcc 7.3.0编译其2.1版本时,编 ...

  5. ifconfig command not found

    CentOS minimal 命令做了修改 可以运行 ip addr

  6. 移远EC20的使用

    一 发短信 3. 推荐短信流程3.1 查询 短信存储区AT+CPMS?+CPMS: "ME",19,255,"ME",19,255,"ME" ...

  7. Fiddler使用三(Fiddler内置命令)

    参考:http://blog.csdn.net/ohmygirl/article/details/17855031 一. Fiddler内置命令. 上一节使用Fiddler进行抓包分析中,介绍到,在w ...

  8. MySql的视图

    视图是从一个或多个表中导出的表.是一种虚拟存在的表.视图就像一个窗口,通过这个窗口可以看到系统专门提供的数据.这样,用户可以不用看到整个数据库表中数据,而只关心对自己有用的数据.视图可以使用户的操作更 ...

  9. 项目管理系列--谷歌的code review

    Google 开源项目风格指南 (中文版) 在线文档托管在 ReadTheDocs : 在线阅读最新版本 中文风格指南 GitHub 托管地址:zh-google-styleguide 声明. 本项目 ...

  10. svn update 报错,必须先cleanup,然后cleanup失败解决方法

    一 问题描述: 1.svn update失败,提示已被locked,请执行cleanup 2.执行svn cleanup,提示cleanup failed to process the followi ...