1.需要添加flink-streaming-scala_2.11的pom文件
2.如果报隐式转换失败:Error:(20, 31) could not find implicit value for evidence parameter of type org.apache.flink.api.common.typeinfo.TypeInformation[String]
在代码中引入一下包:
import org.apache.flink.streaming.api.scala._
如果数据是有限的(静态数据集),我们可以引入以下包:
import org.apache.flink.api.scala._
3.完整代码
import java.util.Properties
import org.apache.flink.streaming.api.scala._
import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer
object KafkaWindowWordCount {
def main(args: Array[String]): Unit = {
// get the execution environment
val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
val properties= new Properties()
properties.setProperty(“bootstrap.servers”, “localhost:9092”)
properties.setProperty(“group.id”, “flink_consumer”)
val consumer = new FlinkKafkaConsumer[String]("demo", new SimpleStringSchema, properties)
val stream = env.addSource(consumer)
val word=stream.flatMap{string=>string.split(" ")}
.map{word=>WordWithCount(word,1)}
.keyBy("word")
.timeWindow(Time.seconds(5), Time.seconds(1))
.sum("count")
word.print().setParallelism(1)
env.execute("Kafka Window WordCount")
}
// Data type for words with count
case class WordWithCount(word: String, count: Long)
}