kafka-connect-transforms 中文亂碼

kafka-connect-transforms 中文亂碼

問題描述

目前使用kafka-connect將分佈式數據採集到集中式數據庫,在採集時,需要追加數據來源標識,其中包含中文內容;

使用notepad++編輯源端配置文件connect-jdbc-source.properties,示例如下:

# 轉換處理
transforms=insertField
transforms.insertField.type=org.apache.kafka.connect.transforms.InsertField$Value
transforms.insertField.static.field=jgmc
transforms.insertField.static.value=xxx社區

但是目標端接收該數據時,數據發生亂碼,顯示爲:

xxx社区

解決辦法

檢查kafka源碼,發現其使用Properties類加載配置文件,代碼片段如下:

    /**
     * Read a properties file from the given path
     * @param filename The path of the file to read
     * @param onlyIncludeKeys When non-null, only return values associated with these keys and ignore all others
     * @return the loaded properties
     */
    public static Properties loadProps(String filename, List<String> onlyIncludeKeys) throws IOException {
        Properties props = new Properties();

        if (filename != null) {
            try (InputStream propStream = Files.newInputStream(Paths.get(filename))) {
                props.load(propStream);
            }
        } else {
            System.out.println("Did not load any properties since the property file is not specified");
        }

        if (onlyIncludeKeys == null || onlyIncludeKeys.isEmpty())
            return props;
        Properties requestedProps = new Properties();
        onlyIncludeKeys.forEach(key -> {
            String value = props.getProperty(key);
            if (value != null)
                requestedProps.setProperty(key, value);
        });
        return requestedProps;
    }

使用該代碼片段,在eclipse中編寫測試類,直接讀取配置文件確實會出現同樣問題。

此時使用eclipse打開該配置文件,發現同樣顯示亂碼。

嘗試直接在eclipse中編輯該配置文件,添加中文xxx社區,得到的輸出是xxx\u793E\u533A,格式如下:

# 轉換處理
transforms=insertField
transforms.insertField.type=org.apache.kafka.connect.transforms.InsertField$Value
transforms.insertField.static.field=jgmc
transforms.insertField.static.value=xxx\u793E\u533A

此時再次執行測試類,發現輸出正常。

按照上述方式修改kafka-connect配置文件,中文信息可以正確顯示到目標數據庫了,問題解決。

截圖如下

id=22 爲異常數據;
id=23爲修改配置後的正常數據;
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章