簡體   English   中英

使用 Google Cloud Dataflow 在 Apache Beam 中進行 Json 驗證

[英]Json Validation in Apache beam using Google Cloud Dataflow

我正在嘗試使用 Apache beam Java SDK 編寫過濾器轉換,我需要過濾掉無效的 Json 消息。

如果我為每個元素驗證創建一個新的 Gson 對象,則實現工作正常。 但是我想避免為每個元素創建 Gson 對象(吞吐量為 1K/秒)並驗證 json。

我在開始時創建一個常量 Gson 對象並在靜態塊中初始化它。 這種方法行不通。 不確定為什么不能使用同一個對象來解析多個元素,因為我們在處理過程中沒有改變對象的狀態?

// Gson object declared as constant
private static final Gson gsonObj=new Gson();

// Initialized GSon object during class loading before main method invocation
static {
    gsonObj = new Gson();
}

....

/*
enum to validate json messages.
 */
enum InputValidation implements SerializableFunction<String, Boolean> {
    VALID {
        @Override
        public Boolean apply(String input) {
            try {
                gsonObj.fromJson(input, Object.class);
                return true;
            } catch(com.google.gson.JsonSyntaxException ex) {
                return false;
            }
        }
    }
}

使用 TupleTag 過濾掉記錄,而不是 'enum InputValidation implements'。 使用以下代碼過濾掉無法解析的 json 行。

Pipeline p = Pipeline.create(options);

TupleTag<String> successParse = new TupleTag<String>();
TupleTag<String> failParse = new TupleTag<String>();

private static final Gson gsonObj=new Gson();

PCollectionTuple = input.apply(ParDo.of(new DoFn<String, String>(){
    @ProcessElement
    public void processElement(ProcessContext c) {
        try {
            gsonObj.fromJson(c.element(), Object.class);
            c.output(successParse,c.element());
        } catch {
            c.output(failParse,c.element());
        }
    }
}).withOutputTags(successParse, TupleTagList.of(failParse)));

上面的代碼在我的情況下起作用,並且是過濾掉記錄的最佳解決方案。

這是官方文檔示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM