could not find implicit value for evidence parameter of type TypeInformation[String]

demo代码:

object SocketWindowWordCount {

  def main(args: Array[String]): Unit = {

    val env: StreamExecutionEnvironment  = StreamExecutionEnvironment.getExecutionEnvironment
   
    val text: DataStream[String] = env.socketTextStream("10.202.42.36",9000, '\n')

    val windowCounts = text.flatMap(w => w.split("\\s")).map(w => WordWithCount(w, 1)).keyBy("word").timeWindow(Time.seconds(5), Time.seconds(1)).sum("count")

    windowCounts.print().setParallelism(1)

    env.execute("Socket Window WordCount")
  }

  case class WordWithCount(value: String, i: Long)
}
编译报错:

报错分析:这种异常的发生通常是因为程序需要一个隐式参数(implicit parameter),参考map或flatMap在flink中的源码:

/**
 * Creates a new DataStream by applying the given function to every element and flattening
 * the results.
 */
def flatMap[R: TypeInformation](fun: T => TraversableOnce[R]): DataStream[R] = {
  if (fun == null) {
    throw new NullPointerException("FlatMap function must not be null.")
  }
  val cleanFun = clean(fun)
  val flatMapper = new FlatMapFunction[T, R] {
    def flatMap(in: T, out: Collector[R]) { cleanFun(in) foreach out.collect }
  }
  flatMap(flatMapper)
}
 
/**
 * Creates a new DataStream by applying the given function to every element of this DataStream.
 */
def map[R: TypeInformation](fun: T => R): DataStream[R] = {
  if (fun == null) {
    throw new NullPointerException("Map function must not be null.")
  }
  val cleanFun = clean(fun)
  val mapper = new MapFunction[T, R] {
    def map(in: T): R = cleanFun(in)
  }

  map(mapper)
}
方法的定义中有个  [R: TypeInformation]  ,但程序并没有指定任何有关隐式参数的定义,编译代码无法创建TypeInformation,所以出现上面提到的异常信息。

解决方案:

1) 我们可以直接在代码里面加上以下的代码:

implicit val typeInfo = TypeInformation.of(classOf[Int])

然后再去编译代码就不会出现上面的异常。
2) 但是这并不是Flink推荐我们去做的,推荐的做法是在代码中引入一下包:

import org.apache.flink.streaming.api.scala. _

如果数据是有限的(静态数据集),我们可以引入以下包:

import org.apache.flink.api.scala. _

然后即可解决上面的异常信息。

备注:最重要的是 Scala Version 正确。 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值