Implement new flink-connector-rocketmq base on FLIP-27/FLIP-191 (#94)

151 files changed
tree: 6ab22cd08d0fb9bbb3c2eecea3065de3e0aaeb6c
  1. src/
  2. style/
  3. .asf.yaml
  4. .gitignore
  5. .travis.yml
  8. pom.xml


Build Status Coverage Status License Average time to resolve an issue Percentage of issues still open Twitter Follow

RocketMQ integration for Apache Flink. This module includes the RocketMQ source and sink that allows a flink job to either write messages into a topic or read from topics in a flink job.


To use the RocketMQSourceFunction, you construct an instance of it by specifying a KeyValueDeserializationSchema instance and a Properties instance which including rocketmq configs. RocketMQSourceFunction(KeyValueDeserializationSchema<OUT> schema, Properties props) The RocketMQSourceFunction is based on RocketMQ pull consumer mode, and provides exactly once reliability guarantees when checkpoints are enabled. Otherwise, the source doesn't provide any reliability guarantees.


The main API for deserializing topic and tags is the org.apache.rocketmq.flink.legacy.common.serialization.KeyValueDeserializationSchema interface. rocketmq-flink includes general purpose KeyValueDeserializationSchema implementations called SimpleKeyValueDeserializationSchema.

public interface KeyValueDeserializationSchema<T> extends ResultTypeQueryable<T>, Serializable {
    T deserializeKeyAndValue(byte[] key, byte[] value);


To use the RocketMQSink, you construct an instance of it by specifying KeyValueSerializationSchema & TopicSelector instances and a Properties instance which including rocketmq configs. RocketMQSink(KeyValueSerializationSchema<IN> schema, TopicSelector<IN> topicSelector, Properties props) The RocketMQSink provides at-least-once reliability guarantees when checkpoints are enabled and withBatchFlushOnCheckpoint(true) is set. Otherwise, the sink reliability guarantees depends on rocketmq producer's retry policy, for this case, the messages sending way is sync by default, but you can change it by invoking withAsync(true).


The main API for serializing topic and tags is the org.apache.rocketmq.flink.legacy.common.serialization.KeyValueSerializationSchema interface. rocketmq-flink includes general purpose KeyValueSerializationSchema implementations called SimpleKeyValueSerializationSchema.

public interface KeyValueSerializationSchema<T> extends Serializable {

    byte[] serializeKey(T tuple);

    byte[] serializeValue(T tuple);


The main API for selecting topic and tags is the org.apache.rocketmq.flink.legacy.common.selector.TopicSelector interface. rocketmq-flink includes general purpose TopicSelector implementations called DefaultTopicSelector and SimpleTopicSelector.

public interface TopicSelector<T> extends Serializable {

    String getTopic(T tuple);

    String getTag(T tuple);


The following is an example which receive messages from RocketMQ brokers and send messages to broker after processing.

StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

       // enable checkpoint

       Properties consumerProps = new Properties();
       consumerProps.setProperty(RocketMQConfig.NAME_SERVER_ADDR, "localhost:9876");
       consumerProps.setProperty(RocketMQConfig.CONSUMER_GROUP, "c002");
       consumerProps.setProperty(RocketMQConfig.CONSUMER_TOPIC, "flink-source2");

       Properties producerProps = new Properties();
       producerProps.setProperty(RocketMQConfig.NAME_SERVER_ADDR, "localhost:9876");

       RocketMQSourceFunction<Map<Object,Object>> source = new RocketMQSourceFunction(
               new SimpleKeyValueDeserializationSchema("id", "address"), consumerProps);
       // use group offsets.
       // If there is no committed offset,consumer would start from the latest offset.
           .process(new ProcessFunction<Map<Object, Object>, Map<Object, Object>>() {
               public void processElement(
                       Map<Object, Object> in,
                       Context ctx,
                       Collector<Map<Object, Object>> out) {
                   HashMap result = new HashMap();
                   result.put("id", in.get("id"));
                   String[] arr = in.get("address").toString().split("\\s+");
                   result.put("province", arr[arr.length - 1]);
           .process(new ProcessFunction<Map<Object, Object>, Message>() {
               public void processElement(Map<Object, Object> value, Context ctx, Collector<Message> out) {
                   String jsonString = JSONObject.toJSONString(value);
                   Message message =
                           new Message(
           .addSink(new RocketMQSink(producerProps).withBatchFlushOnCheckpoint(true))

       try {
       } catch (Exception e) {


The following configurations are all from the class org.apache.rocketmq.flink.legacy.RocketMQConfig.

Producer Configurations

nameserver.addressname server address Requirednull
nameserver.poll.intervalname server poll topic info interval30000
brokerserver.heartbeat.intervalbroker server heartbeat interval30000
producer.groupproducer groupUUID.randomUUID().toString()
producer.retry.timesproducer send messages retry times3
producer.timeoutproducer send messages timeout3000

Consumer Configurations

nameserver.addressname server address Requirednull
nameserver.poll.intervalname server poll topic info interval30000
brokerserver.heartbeat.intervalbroker server heartbeat interval30000
consumer.groupconsumer group Requirednull
consumer.topicconsumer topic Requirednull
consumer.tagconsumer topic tag*
consumer.offset.persist.intervalauto commit offset interval5000
consumer.pull.thread.pool.sizeconsumer pull thread pool size20
consumer.batch.sizeconsumer messages batch size32
consumer.delay.when.message.not.foundthe delay time when messages were not found10

Consumer Strategy

RocketMQSourceFunction<String> source = new RocketMQSourceFunction<>(
        new SimpleStringDeserializationSchema(), props);
HashMap<MessageQueue, Long> brokerMap = new HashMap<>();
brokerMap.put(new MessageQueue("tp_driver_tag_sync_back", "broker-a", 1), 201L);
brokerMap.put(new MessageQueue("tp_driver_tag_sync_back", "broker-c", 3), 123L);

RocketMQSourceFunction offer five initialization policies

  • setStartFromEarliest
  • setStartFromLatest
  • setStartFromTimeStamp with timestamp
  • setStartFromGroupOffsets with OffsetResetStrategy
  • setStartFromSpecificOffsets
EARLIESTconsume from the earliest offset after restart with no state
LATESTconsume from the latest offset after restart with no state
TIMESTAMPconsume from the closest timestamp of data in each broker's queue
GROUP_OFFSETS with LATESTIf broker has the committed offset then consume from the next else consume from the latest offset
GROUP_OFFSETS with EARLIESTIf broker has the committed offset ,consume from the next ,otherwise consume from the earlist offset.It's useful when server expand broker
SPECIFIC_OFFSETSconsumer from the specificOffsets in broker‘s queues.Group offsets will be returned from those broker’s queues whose didn't be specified


Only if Flink job starts with none state, these strategies are effective. If the job recovers from the checkpoint, the offset would intialize from the stored data.

RocketMQ SQL Connector

How to create a RocketMQ table

The example below shows how to create a RocketMQ table:

CREATE TABLE rocketmq_source (
  `user_id` BIGINT,
  `item_id` BIGINT,
  `behavior` STRING
) WITH (
  'connector' = 'rocketmq',
  'topic' = 'user_behavior',
  'consumerGroup' = 'behavior_consumer_group',
  'nameServerAddress' = ''

CREATE TABLE rocketmq_sink (
  `user_id` BIGINT,
  `item_id` BIGINT,
  `behavior` STRING
) WITH (
  'connector' = 'rocketmq',
  'topic' = 'user_behavior',
  'produceGroup' = 'behavior_produce_group',
  'nameServerAddress' = ''

Available Metadata

The following connector metadata can be accessed as metadata columns in a table definition.

The R/W column defines whether a metadata field is readable (R) and/or writable (W). Read-only columns must be declared VIRTUAL to exclude them during an INSERT INTO operation.

topicSTRING NOT NULLTopic name of the RocketMQ record.R

The extended CREATE TABLE example demonstrates the syntax for exposing these metadata fields:

CREATE TABLE rocketmq_source (
  `user_id` BIGINT,
  `item_id` BIGINT,
  `behavior` STRING
) WITH (
  'connector' = 'rocketmq',
  'topic' = 'user_behavior',
  'consumerGroup' = 'behavior_consumer_group',
  'nameServerAddress' = ''


Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.