案例演示:检测连续三次登录失败:
import org.apache.flink.cep.scala.CEP
import org.apache.flink.cep.scala.pattern.Pattern
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.time.Time
import scala.collection.Map
/**
* @Author jaffe
* @Date 2020/06/17 08:55
*/
// 检测连续三次登录失败的事件
object CepExample {
case class LoginEvent(userId:String,ip:String,eventType:String,eventTime: Long)
def main(args: Array[String]): Unit = {
val env = StreamExecutionEnvironment.getExecutionEnvironment
env.setParallelism(1)
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
val stream = env
.fromElements(
LoginEvent("user_1", "0.0.0.0", "fail", 1000L),
LoginEvent("user_1", "0.0.0.1", "fail", 2000L),
LoginEvent("user_1", "0.0.0.2", "fail", 3000L),
LoginEvent("user_2", "0.0.0.0", "success", 4000L)
)
.assignAscendingTimestamps(_.eventTime)
.keyBy(_.userId)
// 定义需要匹配的模板
val pattern =Pattern
.begin[LoginEvent]("first").where(_.eventType.equals("fail"))
.next("second").where(_.eventType.equals("fail"))
.next(("third")).where(_.eventType.equals("fail"))
//.begin[LoginEvent]("S").where(_.eventType.equals("success"))
.within(Time.seconds(10))// 10s之内连续三次登录失败
// 第一个参数:需要匹配的流,第二个参数:模板
val patternedStream =CEP.pattern(stream,pattern)
patternedStream.select(func).print()
env.execute()
}
val func = (pattern:Map[String,Iterable[LoginEvent]]) => {
val first = pattern.getOrElse("first",null).iterator.next()
val second = pattern.getOrElse("second",null).iterator.next()
val third = pattern.getOrElse("third",null).iterator.next()
//val s = pattern.getOrElse("S",null).iterator.next()
first.userId + "连续三次登录失败!"
}
}
val pattern =Pattern
.begin[LoginEvent]("x")
.times(3)
.where(_.eventType.equals("fail"))
.within(Time.seconds(10))
1.个体模式可以包括“单例(singleton)模式”和“循环(looping)模式”
2.条件:
每个模式都需要指定触发条件,作为模式是否接受事件进入的判断依据
CEP 中的个体模式主要通过调用 .where() .or() 和 .until() 来指定条件
按不同的调用方式,可以分成以下几类:
简单条件(Simple Condition)
通过 .where() 方法对事件中的字段进行判断筛选,决定是否接受该事件
组合条件(Combining Condition)
将简单条件进行合并;.or() 方法表示或逻辑相连,where 的直接组合就是 AND
终止条件(Stop Condition)
如果使用了 oneOrMore 或者 oneOrMore.optional,建议使用 .until() 作为终止条件,以便清理状态
迭代条件(Iterative Condition)
能够对模式之前所有接收的事件进行处理
调用 .where( (value, ctx) => {…} ),可以调用 ctx.getEventsForPattern(“name”)
所有事件按照严格的顺序出现,中间没有任何不匹配的事件,由 .next() 指定
例如对于模式”a next b”,事件序列 [a, c, b1, b2] 没有匹配
允许中间出现不匹配的事件,由 .followedBy() 指定
例如对于模式”a followedBy b”,事件序列 [a, c, b1, b2] 匹配为 {a, b1}
进一步放宽条件,之前已经匹配过的事件也可以再次使用,由 .followedByAny() 指定
例如对于模式”a followedByAny b”,事件序列 [a, c, b1, b2] 匹配为 {a, b1},{a, b2}
需要注意:
所有模式序列必须以 .begin() 开始
模式序列不能以 .notFollowedBy() 结束
“not” 类型的模式不能被 optional 所修饰
此外,还可以为模式指定时间约束,用来要求在多长时间内匹配有效:
案例演示1:订单超时需求
import org.apache.flink.cep.scala.CEP
import org.apache.flink.cep.scala.pattern.Pattern
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.util.Collector
import scala.collection.Map
/**
* @Author jaffe
* @Date 2020/06/17 10:45
*/
object OrderTimeout {
case class OrderEvent(orderId: String, eventType: String, eventTime: Long)
def main(args: Array[String]): Unit = {
val env = StreamExecutionEnvironment.getExecutionEnvironment
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
env.setParallelism(1)
val stream = env
.fromElements(
OrderEvent("order_1", "create", 2000L),
OrderEvent("order_2", "create", 3000L),
OrderEvent("order_2", "pay", 4000L)
)
.assignAscendingTimestamps(_.eventTime)
.keyBy(_.orderId)
val pattern = Pattern
.begin[OrderEvent]("create").where(_.eventType.equals("create"))
.next("pay").where(_.eventType.equals("pay"))
.within(Time.seconds(5))
val patternedStream = CEP.pattern(stream, pattern)
// 用来输出超时订单的侧输出标签
val orderTimeOutput = new OutputTag[String]("timeout")
// 用来处理超时订单的函数
val timeOutFunc = (map: Map[String, Iterable[OrderEvent]], ts: Long, out: Collector[String]) => {
println("ts" + ts)
val orderStart = map("create").head
// 将报警信息发送到侧输出流去
out.collect(orderStart.orderId + "没有支付")
}
val selectFunc = (map: Map[String, Iterable[OrderEvent]], out: Collector[String]) => {
val order = map("pay").head
out.collect(order.orderId + "已经支付")
}
val outputStream = patternedStream
// 第一个参数:用来输出超时事件的侧输出标签
// 第二个参数:用来输出超时事件的函数
// 第三个参数:用来输出没有超时的事件的函数
.flatSelect(orderTimeOutput)(timeOutFunc)(selectFunc)
outputStream.print()
outputStream.getSideOutput(new OutputTag[String]("timeout")).print()
env.execute()
}
}
案例演示2:使用底层API实现订单超时需求
import org.apache.flink.api.common.state.ValueStateDescriptor
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.functions.KeyedProcessFunction
import org.apache.flink.streaming.api.scala._
import org.apache.flink.util.Collector
/**
* @Author jaffe
* @Date 2020/06/17 11:46
*/
object OrderTimeoutWithoutCep {
case class OrderEvent(orderId: String, eventType: String, eventTime: Long)
def main(args: Array[String]): Unit = {
val env = StreamExecutionEnvironment.getExecutionEnvironment
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
env.setParallelism(1)
val stream = env
.fromElements(
OrderEvent("order_1", "create", 2000L),
OrderEvent("order_2", "create", 3000L),
OrderEvent("order_2", "pay", 4000L)
)
.assignAscendingTimestamps(_.eventTime)
.keyBy(_.orderId)
.process(new OrderTimeoutFunc)
val timeoutOutput = new OutputTag[String]("timeout")
stream.getSideOutput(timeoutOutput).print()
stream.print()
env.execute()
}
class OrderTimeoutFunc extends KeyedProcessFunction[String, OrderEvent, String] {
lazy val orderState = getRuntimeContext.getState(
new ValueStateDescriptor[OrderEvent]("save order", classOf[OrderEvent])
)
override def processElement(i: OrderEvent, context: KeyedProcessFunction[String, OrderEvent, String]#Context, collector: Collector[String]): Unit = {
if (i.eventType.equals("create")) {
if (orderState.value() == null) {
orderState.update(i)
context.timerService().registerEventTimeTimer(i.eventTime + 5000L)
}
} else {
orderState.update(i)
collector.collect("已经支付的订单ID是:" + i.orderId)
}
}
override def onTimer(timestamp: Long, ctx: KeyedProcessFunction[String, OrderEvent, String]#OnTimerContext, out: Collector[String]): Unit = {
val order = orderState.value()
if (order != null && order.eventType.equals("create")) {
ctx.output(new OutputTag[String]("timeout"), "超时订单的ID为:" + order.orderId)
}
orderState.clear()
}
}
}