Apach Zepplein使用Livy解释器中文不能被解析问题

来源:互联网 发布:数控打圈机编程视频 编辑:程序博客网 时间:2024/06/08 14:53

一 .起因

在配置好Zeppelin 和 Livy之后,日常使用的过程中发现,Spark sql或者filter等操作中带上中文的话返回结果总是为空。 但是日常使用中并不是所有信息都可以用英文表示,例如家庭地址就不方便用英文表示。


二 . 查找问题由来

问题一出现,我就立马联想到了编码问题,毕竟之前被python unicode编码折腾过。但是zeppelin,livy, spark这三个地方到底是哪里的交互中编码出了问题呢?

在这篇文章中,作者也在spark上碰到了类似的字符串编码问题。

按照他的思路,我试着查看zeppelin的log和livy 的log.

但是zeppelin的log中所有中文都可以正常显示,livy的log则很不完善,并没有记录收到请求的相关信息。

然后我试着在使用python 直接仿照livy 官网的例子向livy 直接发送带中文spark sql查询,结果可以正确返回结果。

同时查看yarn logs,可以发现如下的对比。

 

ZEPPELIN 发送到livy的请求产生的log:

INFO execution.SparkSqlParser: Parsing command: label = '?' 

17/06/12 18:05:17 INFO execution.SparkSqlParser: Parsing command: label = '?' 

17/06/12 18:05:17 INFO datasources.FileSourceStrategy: Pruning directories with: 

17/06/12 18:05:17 INFO datasources.FileSourceStrategy: Post-Scan Filters: isnotnull(label#2),(label#2 = ?) 

17/06/12 18:05:17 INFO datasources.FileSourceStrategy: Output Data Schema: struct<id: bigint, member_id: bigint, label: string, address: string, address_detail: string ... 16 more fields> 

17/06/12 18:05:17 INFO datasources.FileSourceStrategy: Pushed Filters: IsNotNull(label),EqualTo(label,?) 

 

 


而直接post到livy的请求产生的spark 任务的 yarn log里面可以看到是确实有中文的 

17/06/12 22:05:46 INFO execution.SparkSqlParser: Parsing command: label = '家' 

17/06/12 22:05:46 INFO datasources.FileSourceStrategy: Pruning directories with: 

17/06/12 22:05:46 INFO datasources.FileSourceStrategy: Post-Scan Filters: isnotnull(label#2),(label#2 = 家) 

17/06/12 22:05:46 INFO datasources.FileSourceStrategy: Output Data Schema: struct<id: bigint, member_id: bigint, label: string, address: string, address_detail: string ... 16 more fields> 

17/06/12 22:05:46 INFO datasources.FileSourceStrategy: Pushed Filters: IsNotNull(label),EqualTo(label,家)


说明问题出在zeppelin向livy发送请求的过程中。进一步查看log,发现zepplein 与livy 交互使用了callRestAPI这函数,位于BaseLivyInterpreter.java文件中。


在callRestAPI文件中,zeppelin使用了restTemplate 这个spring 自带的restful请求函数,然而从这so讨论可以知道,spring 默认使用ISO-8895-1 编码发送请求,但是这个编码是不支持中文的。


三. 解决问题

修改spring 发送restful请求时的默认编码即可。

在BaseLivyInterpreter.java中

用headers.add("Content-Type",MediaType.APPLICATION_JSON_UTF8_VALUE)

替换headers.add("Content-Type","application/json") 

并在开头增加必要的import就可以了