Clojure:实现有状态 Java 接口

Clojure: implementing stateful Java interface

Kafka Streams has an interface, Processor, the implementation of which is stateful. An example implementation 开发者指南中给出的是:

public class WordCountProcessor implements Processor<String, String> {

  private ProcessorContext context;
  private KeyValueStore<String, Long> kvStore;

  @Override
  @SuppressWarnings("unchecked")
  public void init(ProcessorContext context) {
      // keep the processor context locally because we need it in punctuate() and commit()
      this.context = context;

      // call this processor's punctuate() method every 1000 time units.
      this.context.schedule(1000);

      // retrieve the key-value store named "Counts"
      kvStore = (KeyValueStore) context.getStateStore("Counts");
  }

  @Override
  public void process(String dummy, String line) {
      String[] words = line.toLowerCase().split(" ");

      for (String word : words) {
          Long oldValue = kvStore.get(word);
          if (oldValue == null) {
              kvStore.put(word, 1L);
          } else {
              kvStore.put(word, oldValue + 1L);
          }
      }
  }

  @Override
  public void punctuate(long timestamp) {
      KeyValueIterator<String, Long> iter = this.kvStore.all();
      while (iter.hasNext()) {
          KeyValue<String, Long> entry = iter.next();
          context.forward(entry.key, entry.value.toString());
      }
      iter.close();
      // commit the current processing progress
      context.commit();
  }

  @Override
  public void close() {
      // close the key-value store
      kvStore.close();
  }

}

init 方法初始化 WordCountProcessor 的内部状态,例如检索键值存储。其他方法,如 processclose,使用此状态。

我不清楚如何在 Clojure 中 reify 这样的接口。我们如何将 init 检索到的状态传递给 processclose 等?

使用闭包?

我的一个想法是使用闭包:

(let [ctx (atom nil)]
  (reify Processor
    (close [this]
      ;; Do something w/ ctx
      )
    (init [this context]
      (reset! ctx context))
    (process [this k v]
      ;; Do something w/ ctx
      )
    (punctuate [this timestamp]
      ;; Do something w/ ctx
      )))

烦人的是,我们每次都必须从 ProcessorContext 对象开始,因此键值存储代码将在所有需要键值存储的方法中重复。

我没有看到解决这个问题的(通用)方法,但根据具体情况,我们可以用方法需要的更具体的状态替换 ctx 原子。

有没有更好的方法?

关闭原子将是实现它的主要方法。你原来的 class 有两个字段,所以你可以关闭两个原子来获得相同的效果

(let [ctx (atom nil)
      kv-store (atom nil)]
  (reify Processor
    ,,,
    (init [this context]
      (reset! ctx context)
      (reset! kv-store (.getStateStore context "Counts")))
    ,,,))

如果这仍然太乏味,那么您可以添加一些方便的函数,这些函数也可以关闭原子

(let [ctx (atom nil)
      kv-store (atom nil)]

  (def kv-get [key]
    (.get @kv-store key))

  (def kv-all []
    (iterator-seq (.all @kv-store)))

  (def kv-put [key value]
    (.put @kv-store key value))

  (reify Processor
    ,,,
    (init [this context]
      (reset! ctx context)
      (reset! kv-store (.getStateStore context "Counts")))
    ,,,
  (punctuate [this timestamp]
    (do-seq [x (kv-all)]
      ,,,)
  )))

另一种方法是使用 gen-class,但我认为使用 reify 会更好。