在本次spark2.1进行数据处理的过程中,遇到的问题是:
val spark = SparkSession.builder
.config(sparkConf).getOrCreate()
//创建jdbc连接信息
val uri = url + "?user=" + username + "&password=" + password + "&useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true"
//....
val df_source: DataFrame = spark.read.jdbc(uri, "table_name", prop)
//.....
val df = spark.sql(sql).as[user].rdd
val DF = df.map({
item=>
item........
}).toDF()
DF.show()
//中文显示正常
.....
DF.write.mode("append").jdbc(uri,s"table_name",prop)
如上,jdbc读取中文显示正常。
本地idea环境上:
1.数据处理后(map算子处理后),中文显示正常;
2.Dataframe通过jdbc写入mysql,中文显示正常;
集群环境上:
spark-on-yarn模式,出现中文无法正常显示,中文乱码?????? (iso-8859-1转UTF-8C出现乱码);
上述处理过程:
1.jdbc url,添加了 &useUnicode=true&characterEncoding=UTF-8;
2.mysql数据库的默认字符集修改为utf-8;
3.集群环境编码格式(client以及executor):调整为 LANG="zh_CN.UTF-8"(centos执行locale查看);
4.scala脚本中编码转换位置,进行了格式转换:
java 模块
byte[] re = ss.getBytes("UTF-8");
String result = new String(re, "ISO8859-1");
.....
.....
.....
scala 模块
val ps= new String(result.getBytes("ISO8859-1"),"UTF-8")
上述处理后,依旧是中文乱码?????
5.spark submit 执行脚本时,添加参数项:
--conf spark.executor.extraJavaOptions="-Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8"
问题解决,中文显示正常,写入数据库显示正常。