在这个项目中,我尝试使用flink使用kafka主题中的数据,然后使用flink cep处理流以检测模式。使用kafka connect的部分可以工作,并且正在获取数据,但是cep部分由于某种原因不能工作。我在这个项目中使用scala。
内部版本.sbt:
version := "0.1"
scalaVersion := "2.11.12"
libraryDependencies += "org.apache.flink" %% "flink-streaming-scala" % "1.12.2"
libraryDependencies += "org.apache.kafka" %% "kafka" % "2.3.0"
libraryDependencies += "org.apache.flink" %% "flink-connector-kafka" % "1.12.2"
libraryDependencies += "org.apache.flink" %% "flink-cep-scala" % "1.12.2"
主代码:
import org.apache.flink.api.common.serialization.SimpleStringSchema
import java.util
import java.util.Properties
import org.apache.flink.cep.PatternSelectFunction
import org.apache.flink.cep.scala.CEP
import org.apache.flink.streaming.api.scala._
import org.apache.flink.cep.scala.pattern.Pattern
import org.apache.flink.streaming.api.scala.{DataStream, StreamExecutionEnvironment}
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer
import org.apache.flink.cep.pattern.conditions.IterativeCondition
object flinkExample {
def main(args: Array[String]): Unit = {
val CLOSE_THRESHOLD: Double = 140.00
val properties = new Properties()
properties.setProperty("bootstrap.servers", "localhost:9092")
properties.setProperty("zookeeper.connect", "localhost:2181")
properties.setProperty("group.id", "test")
val consumer = new FlinkKafkaConsumer[String]("test", new SimpleStringSchema(), properties)
consumer.setStartFromEarliest
val see: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
val src: DataStream[String] = see.addSource(consumer)
val keyedStream: DataStream[Stock] = src.map(v => v)
.map {
v =>
val data = v.split(":")
val date = data(0)
val close = data(1).toDouble
Stock(date,close)
}
val pat = Pattern
.begin[Stock]("start")
.where(_.Adj_Close > CLOSE_THRESHOLD)
val patternStream = CEP.pattern(keyedStream, pat)
val result = patternStream.select(
patternSelectFunction = new PatternSelectFunction[Stock, String]() {
override def select(pattern: util.Map[String, util.List[Stock]]): String = {
val data = pattern.get("first").get(0)
data.toString
}
}
)
result.print()
see.execute("ASK Flink Kafka")
}
case class Stock(date: String,
Adj_Close: Double)
{
override def toString: String = s"Stock date: $date, Adj Close: $Adj_Close"
}
}
来自Kafka的数据是字符串格式的:“date:value"
scala版本:2.11.12 flink版本:1.12.2 kafka版本:2.3.0
我使用:sbt assembly构建项目,然后在flink Jmeter 板中部署jar。
1条答案
按热度按时间klh5stk11#
与
pattern.get("first")
您正在从模式序列中选择一个名为“first”的模式,但该模式序列只有一个名为“start”的模式。试着把“第一个”改成“开始”。此外,cep必须能够将流按时间顺序排序,以便进行模式匹配。你应该定义一个水印策略。对于处理时间语义,可以使用
WatermarkStrategy.noWatermarks()
.