触发后取消Kafka Streams上的Punctuator

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (59)

我在变压器上创建了一个预定的标点符号,我安排它定期运行(使用kafka v2.1.0)。每次我接受一个特定的密钥,我都会创建一个像这样的新密钥

        scheduled = context.schedule (Duration.ofMillis(scheduleTime),
             PunctuationType.WALL_CLOCK_TIME,new CustomPunctuator(context, customStateStoreName));

我的问题是,我创建的所有这些标点符号都在不断运行,我找不到取消它们的方法。我在互联网上找到了一个片段

    private Cancellable scheduled;

    @Override
    public void init(PorcessorContext processContext) {
        this.context = processorContext;
        scheduled = context.schedule(TimeUnit.SECONDS.toMillis(5), PunctuationType.WALL_CLOCK_TIME,
                                     this::punctuateCancel);
    }

    private void punctuateCancel(long timestamp) {
        scheduled.cancel();
    }

但不幸的是,这似乎只取消了最新创建的标点符号。

我正在编辑我的帖子只是为了进一步了解我的方法以及这与wardzinia的评论有何关联。所以我的方法非常类似于使用Map,因为我需要每个事件键只有一个标点符号,所以在我的Transformer类中我启动

   private Map<String,Cancellable> scheduled  = new HashMap<>();

在我的转换方法中,我执行下面的代码

{
 final Cancellable cancelSched = scheduled.get(recordKey);

 // Every time I get a new event I cancel my previous Punctuator
 // and schedule a new one ( context.schedule a few lines later)

 if(cancelSched != null)
    cancelSched.cancel();

 // This is supposed to work like a closure by capturing the currentCancellable which in the next statement
 // is moved to the scheduled map. Scheduled map at any point will have the only active Punctuator for a
 // specific String as it is constantly renewed
 // Note: Previous registered punctuators have already been cancelled as it can be seen by the previous
 // statement (cancelSched.cancel();)

 Cancellable currentCancellable = context.schedule(Duration.ofMillis(scheduleTime), PunctuationType.WALL_CLOCK_TIME,
                new CustomPunctuator(context, recordKey ,()-> scheduled ));

 // Update Active Punctuators for a specific key.

 scheduled.put(recordKey,currentCancellable);   
}

我在我的Punctuator标点符号方法上使用该注册回调来取消最后一个活动的标点符号。它似乎工作(虽然不确定),但它感觉非常“hacky”,而不是那种当然可取的解决方案。

那么如何在触发后取消标点符号。有办法解决这个问题吗?

提问于
用户回答回答于

你可以做的一件事是:

class CustomPunctuator implements Punctuator {
  final Cancellable schedule;

  public void punctuate(final long timestamp) {
    // business logic
    if (/* do cancel */) {
      schedule.cancel()
    }
  }
}

// registering a punctuation
{
  final CustomPunctuator punctuation = new CustomPunctuator();
  final Cancellable currentCancellable = context.schedule(
    Duration.ofMillis(scheduleTime),
    PunctuationType.WALL_CLOCK_TIME,
    punctuation);

  punctuation.schedule = currentCancellable;
}

这样,您不需要维护HashMap并为每个CustomPunctuator实例提供取消自身的方法。

扫码关注云+社区

领取腾讯云代金券