Commit 799702f6 authored by liuwenhui's avatar liuwenhui

Kafka添加key

parent 602845f1
package org.dinky.cdc.kafka;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
import java.util.LinkedHashMap;
import java.util.Map;
public class KeySerializationSchema implements SerializationSchema<String> {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Override
public byte[] serialize(String element) {
try {
Map<String, Object> map = OBJECT_MAPPER.readValue(element, Map.class);
LinkedHashMap source = (LinkedHashMap) map.get("source");
String db = source.get("db").toString();
String tableName = source.get("table").toString();
String schema = source.containsKey("schema") ? source.get("schema").toString() : "";
if (schema.isEmpty()) {
return (db + "." + tableName).getBytes();
} else {
return (db + "." + schema + "." + tableName).getBytes();
}
} catch (Exception e) {
// 记录更详细的日志信息
System.err.println("Failed to serialize element: " + element);
e.printStackTrace();
// 返回空字节数组,避免返回 null
return new byte[0];
}
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment