Kafka自定义分区规则

分区规则:

public class Partitioner1 implements Partitioner{

    public Partitioner1() {

    }

    public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
        List<PartitionInfo> partitions = cluster.partitionsForTopic(topic);
        int num = partitions.size();
        int partNum = 0;
        try {
            partNum = Integer.parseInt((String) key);
        } catch (Exception e) {
            partNum = key.hashCode();
        }
        return Math.abs(partNum % num);
    }

    public void close() {

    }

    public void configure(Map<String, ?> configs) {

    }
}

生产者:

public class DProducer {

    public static void main(String[] args){
        Properties prop = new Properties();
        prop.put("bootstrap.servers","node:9092,node:9093,node:9094");
        prop.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        prop.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        prop.put("partitioner.class", "com.kafka.d.Partitioner1");

        Producer producer = new KafkaProducer(prop);

        for(int i = 0; i < 10; i++) {
            producer.send(new ProducerRecord("test2",Integer.toString(i), Integer.toString(i)));
        }
        producer.close();
    }
}

消费者:

public class DConsumer {

    public static void main(String[] args) {
        Properties prop = new Properties();
        prop.put("bootstrap.servers","node:9092");
        prop.put("group.id","test7");
        prop.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        prop.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        Consumer consumer = new KafkaConsumer(prop);

        consumer.subscribe(Arrays.asList("test2"));
        while (true) {
            ConsumerRecords<String, String> c = consumer.poll(100);
            for(ConsumerRecord<String, String> c1: c) {
                System.out.println("Key: " + c1.key() + " Value: " + c1.value() + " Offset: " + c1.offset() + " Partitions: " + c1.partition());

            }
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值