Flink使用Java自定义类设置基本的Kafka生产者使用者

时间:2020-03-09 07:28:22

标签: serialization apache-kafka deserialization apache-flink flink-streaming

我想在Kafka上使用 Flink 设置一个基本的生产者-消费者,但是我很难通过Java向现有的消费者生产数据。

CLI解决方案

  1. 我使用命令Kafka broker中的kafka_2.11-2.4.0邮政编码设置了https://kafka.apache.org/downloads

    bin/zookeeper-server-start.sh config/zookeeper.properties

    bin/kafka-server-start.sh config/server.properties

  2. 我使用创建一个名为transaction1的主题

    bin/kafka-topics.sh --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1 --topic transactions1

    现在,我可以在命令行上使用生产者和使用者来查看主题是否已创建并起作用。

  3. 要设置使用者,我要运行

    bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic transactions1 --from-beginning

    现在,如果有任何生产者将数据发送到主题transactions1,我将在消费者控制台中看到它。

    我通过运行来测试消费者是否在工作

    bin/kafka-console-producer.sh --broker-list localhost:9092 --topic transactions1

    ,然后在cli中的生产者中输入以下数据行,这些数据行也会显示在消费者cli中。

{“ txnID”:1,“ amt”:100.0,“帐户”:“ AC1”}

{“ txnID”:2,“ amt”:10.0,“帐户”:“ AC2”}

{“ txnID”:3,“ amt”:20.0,“帐户”:“ AC3”}

现在,我想用Java代码复制第3步,即生产者和使用者,这是此问题的核心问题。

  1. 所以我用build.gradle设置了gradle java8项目
...
dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'org.apache.flink', name: 'flink-connector-kafka_2.11', version: '1.9.0'
    compile group: 'org.apache.flink', name: 'flink-core', version: '1.9.0'
    // https://mvnrepository.com/artifact/org.apache.flink/flink-streaming-java
    compile group: 'org.apache.flink', name: 'flink-streaming-java_2.12', version: '1.9.2'
    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'
    compile group: 'com.twitter', name: 'chill-thrift', version: '0.7.6'
    compile group: 'org.apache.thrift', name: 'libthrift', version: '0.11.0'
    compile group: 'com.twitter', name: 'chill-protobuf', version: '0.7.6'
    compile group: 'org.apache.thrift', name: 'protobuf-java', version: '3.7.0'
}
...
  1. 我设置了自定义类Transactions.class,在其中您可以通过扩展与 Flink 相关的类来使用Kryo,Protobuf或TbaseSerializer建议对序列化逻辑进行更改。
import com.google.gson.Gson;
import org.apache.flink.api.common.functions.MapFunction;

public class Transaction {
    public final int txnID;
    public final float amt;
    public final String account;

    public Transaction(int txnID, float amt, String account) {
        this.txnID = txnID;
        this.amt = amt;
        this.account = account;
    }


    public String toJSONString() {
        Gson gson = new Gson();
        return gson.toJson(this);
    }

    public static Transaction fromJSONString(String some) {
        Gson gson = new Gson();
        return gson.fromJson(some, Transaction.class);
    }

    public static MapFunction<String, String> mapTransactions() {
        MapFunction<String, String> map = new MapFunction<String, String>() {
            @Override
            public String map(String value) throws Exception {
                if (value != null || value.trim().length() > 0) {
                    try {
                        return fromJSONString(value).toJSONString();
                    } catch (Exception e) {
                        return "";
                    }
                }
                return "";
            }
        };
        return map;
    }

    @Override
    public String toString() {
        return "Transaction{" +
                "txnID=" + txnID +
                ", amt=" + amt +
                ", account='" + account + '\'' +
                '}';
    }
}
  1. 现在是时候使用Flink生成和消费主题transactions1上的流了。
public class SetupSpike {
    public static void main(String[] args) throws Exception {
        System.out.println("begin");
        List<Transaction> txns = new ArrayList<Transaction>(){{
            add(new Transaction(1, 100, "AC1"));
            add(new Transaction(2, 10, "AC2"));
            add(new Transaction(3, 20, "AC3"));
        }};
        // This list txns needs to be serialized in Flink as Transaction.class->String->ByteArray 
        //via producer and then to the topic in Kafka broker 
        //and deserialized as ByteArray->String->Transaction.class from the Consumer in Flink reading Kafka broker.
        
        String topic = "transactions1";
        Properties properties = new Properties();
        properties.setProperty("bootstrap.servers", "localhost:9092");
        properties.setProperty("zookeeper.connect", "localhost:2181");
        properties.setProperty("group.id", topic);

        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        //env.getConfig().addDefaultKryoSerializer(Transaction.class, TBaseSerializer.class);

        // working Consumer logic below which needs edit if you change serialization
        FlinkKafkaConsumer<String> myConsumer = new FlinkKafkaConsumer<String>(topic, new SimpleStringSchema(), properties);
        myConsumer.setStartFromEarliest();     // start from the earliest record possible
        DataStream<String> stream = env.addSource(myConsumer).map(Transaction::toJSONString);
       
        //working Producer logic below which works if you are sinking a pre-existing DataStream
        //but needs editing to work with Java List<Transaction> datatype.
        System.out.println("sinking expanded stream");
        MapFunction<String, String> etl = new MapFunction<String, String>() {
            @Override
            public String map(String value) throws Exception {
                if (value != null || value.trim().length() > 0) {
                    try {
                        return fromJSONString(value).toJSONString();
                    } catch (Exception e) {
                        return "";
                    }
                }
                return "";
            }
        };
        FlinkKafkaProducer<String> myProducer = new FlinkKafkaProducer<String>(topic,
                new KafkaSerializationSchema<String>() {
                    @Override
                    public ProducerRecord<byte[], byte[]> serialize(String element, @Nullable Long timestamp) {
                        try {
                            System.out.println(element);
                            return new ProducerRecord<byte[], byte[]>(topic, stringToBytes(etl.map(element)));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                }, properties, Semantic.EXACTLY_ONCE);
//        stream.timeWindowAll(Time.minutes(1));
        stream.addSink(myProducer);
        JobExecutionResult execute = env.execute();

    }
}

如您所见,使用提供的列表txns,我无法执行此操作。以上是我可以从Flink文档中收集的工作代码,用于重定向主题流数据并通过Cli生产者手动发送数据。问题是用Java编写了KafkaProducer代码,该代码将数据发送到该主题,而该问题进一步与诸如

  1. 添加时间戳,水印
  2. KeyBy操作
  3. GroupBy / WindowBy操作
  4. 在下沉之前添加自定义ETL逻辑。
  5. Flink中的序列化/反序列化逻辑

与Flink合作的人可以帮助我如何在Flink中生成txnstransactions1的主题,然后验证它是否与Consumer兼容? 您可以在https://github.com/devssh/kafkaFlinkSpike上找到源代码,其目的是生成Flink样板以从中添加“ AC1”的详细信息。一个内存中的商店,并与实时发生的Transaction事件一起将其发送给用户。

1 个答案:

答案 0 :(得分:1)

几个点,没有特定的顺序:

最好不要像下面那样将Flink 1.9.2版和1.9.0版混合使用:

compile group: 'org.apache.flink', name: 'flink-connector-kafka_2.11', version: '1.9.0'
compile group: 'org.apache.flink', name: 'flink-core', version: '1.9.0'
compile group: 'org.apache.flink', name: 'flink-streaming-java_2.12', version: '1.9.2'

有关如何使用时间戳,水印,keyBy,窗口等的教程,请参见online training materials from Ververica

要将List<Transaction> txns用作输入流,可以执行以下操作(docs):

DataStream<Transaction> transactions = env.fromCollection(txns);

有关在使用Flink和Kafka时如何处理序列化/反序列化的示例,请参见Flink Operations Playground,特别是ClickEventDeserializationSchemaClickEventStatisticsSerializationSchema,它们在{{ 3}},并定义了ClickEventCount.java。 (注意:此游乐场尚未针对Flink 1.10进行更新。)