应用场景:使用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. HTML学习-01

    1.标签描述了基本的链接地址/链接目标,该标签作为HTML文档中所有的链接标签的默认链接. 2.如果<head>里面设置了base,那么后面的img图片需要添加的相对路径. 3.不能使用工 ...

  2. springboot 接口返回数据时 net.sf.json.JSONNull["empty"]) 异常

    @ResetController返回数据时出现异常 Could not write JSON: Object is null; nested exception is com.fasterxml.ja ...

  3. Python学习 day13

    一.可迭代对象和迭代器 1.回顾可以被for循环的对象 list.dic.str.set.tuple.文件句柄f.range().enumerate() 只有可迭代对象才能被for循环,当我们遇到一个 ...

  4. Testlink 机器重启后Access denied for user 'admin '@'localhost' (using password: YES)解决

    问题表现: 装完Testlink,重启系统后,在testlink权限未分配会出现如下提示: 1045 - Access denied for user 'Testlink '@'localhost' ...

  5. BAE+Python+Django+Wechatpy+Baidu weather api +微信订阅号 = 实现微信查询天气

    最近想在微信上面实现天气查询,分两个步骤: 1.被动回复:输入天气.xx天气获取天气情况 2.主动推送:每天定时推送天气(针对24小时内产生交互的人) 目前已经实现第一个步骤,如下: 现将实现此功能环 ...

  6. Java万年历,输入年月获取该年月日历表

    //输入年份和月份,打印出这个月的日历表 /* 1.1900年1月1日是星期一 2.计算输入的年份距离1900年有多少天再计算当年1月1日距这个月有多少天 1) 3.总天数%7得出从星期几开始 注:计 ...

  7. 自己用的opensuse源

    utsc_oss               http://mirrors.ustc.edu.cn/opensuse/distribution/13.1/repo/oss/utsc_non_oss  ...

  8. object与byte[]的相互转换、文件与byte数组相互转换

    转载自   https://blog.csdn.net/scimence/article/details/52233656 object与byte[]互转 /// <summary> // ...

  9. 我Java学习时的模样(三)

    读Java源码 平常使用Java的时候,那些集合类使用起来很顺手,但是有没有想过这些集合内部的实现原理是怎样的,它的添加移除都有哪些操作? 有了一些工作经验之后,必须要读一读Java包中的源码,需要知 ...

  10. NPOI 设置导出的excel内容样式

    导出excel时,有时要根据需要加上一些样式,以上几种样式是我在项目中用到的 一.给单元格加背景色只需两步:一是创建单元格背景景色对象:二是给单元格绑定样式 //创建单元格背景颜色对象 HSSFPal ...