使用 apache flink 进行有状态的复杂事件处理

Stateful Complex event processing with apache flink

我想根据具有相同标识符的两个事件来检测两个事件是否在定义的时间范围内发生。例如 DoorEvent 看起来像这样:

<doorevent>
  <door>
    <id>1</id>
    <status>open</status>
  </door>
  <timestamp>12345679</timestamp>
</doorevent> 

<doorevent>
  <door>
    <id>1</id>
    <status>close</status>
  </door>
  <timestamp>23456790</timestamp>
</doorevent>

下例中我的DoorEventjavaclass结构相同

我想检测 id 为 1 的门在打开后 5 分钟内关闭。为此,我尝试使用 Apache flink CEP 库。传入流包含来自假设 20 扇门的所有打开和关闭消息。

Pattern<String, ?> pattern = Pattern.<String>begin("door_open").where(
    new SimpleCondition<String>() {
        private static final long serialVersionUID = 1L;
        public boolean filter(String doorevent) {
            DoorEvent event = new DoorEvent().parseInstance(doorevent, DataType.XML);
            if (event.getDoor().getStatus().equals("open")){
                // save state of door as open
                return true;
            }
            return false;                           
        }
    }
)
.followedByAny("door_close").where(
    new SimpleCondition<String>() {
            private static final long serialVersionUID = 1L;
            public boolean filter(String doorevent) throws JsonParseException, JsonMappingException, IOException {
                DoorEvent event = new DoorEvent().parseInstance(doorevent, DataType.XML);
                if (event.getDoor().getStatus().equals("close")){
                    // check if close is of previously opened door
                    return true;
                }
                return false;
            }
        }
)
.within(Time.minutes(5));

如何在 door_open 中将门 1 的状态保存为打开状态,以便在 door_close 步骤中我知道门 1 是正在关闭的门,而不是其他门?

如果你有 Flink 1.3.0 及以上版本,那么你想做什么就很简单了

您的模式看起来像这样:

Pattern.<DoorEvent>begin("first")
        .where(new SimpleCondition<DoorEvent>() {
          private static final long serialVersionUID = 1390448281048961616L;

          @Override
          public boolean filter(DoorEvent event) throws Exception {
            return event.getDoor().getStatus().equals("open");
          }
        })
        .followedBy("second")
        .where(new IterativeCondition<DoorEvent>() {
          private static final long serialVersionUID = -9216505110246259082L;

          @Override
          public boolean filter(DoorEvent secondEvent, Context<DoorEvent> ctx) throws Exception {

            if (!secondEvent.getDoor().getStatus().equals("close")) {
              return false;
            }

            for (DoorEvent firstEvent : ctx.getEventsForPattern("first")) {
              if (secondEvent.getDoor().getEventID().equals(firstEvent.getDoor().getEventId())) {
                return true;
              }
            }
            return false;
          }
        })
        .within(Time.minutes(5));

所以基本上您可以使用 IterativeConditions 并获取匹配的第一个模式的上下文并迭代该列表,同时比较您需要的模式并按需继续。

IterativeConditions are expensive and should be handled accordingly

有关条件的更多信息,请访问 Flink - Conditions