(4.3)kafka生产者源码——Partitioner分区器,决定消息发送的分区

1:分区器Partitioner

通过类图查看默认的Partitioner接口只有一个实现类DefaultPartitioner,也可以自己实现接口自定义
在这里插入图片描述

1.1:DefaultPartitioner默认分区器

每个topic都有一个固定的随机数作为开头,用于hash计算。

  • 当消息被指定key时,直接计算hash获取分区数。
  • 没有指定key时通过分区自增轮询写入分区中
   public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
        /*获取该topic所有的分区和分区的个数*/
        List<PartitionInfo> partitions = cluster.partitionsForTopic(topic);
        int numPartitions = partitions.size();
        /*大多数情况我们是不指定key的*/
        if (keyBytes == null) {
            int nextValue = nextValue(topic);/*返回该topic所属的随机数*/
            List<PartitionInfo> availablePartitions = cluster.availablePartitionsForTopic(topic);
            if (availablePartitions.size() > 0) {
                int part = Utils.toPositive(nextValue) % availablePartitions.size();
                /*返回分区编码*/
                return availablePartitions.get(part).partition();
            } else {
                // no partitions are available, give a non-available partition
                return Utils.toPositive(nextValue) % numPartitions;
            }
        } else {
            // hash the keyBytes to choose a partition指定了key,哈希keyBytes以选择分区,保证相同的key都进入了一个分区,保证有序性
            return Utils.toPositive(Utils.murmur2(keyBytes)) % numPartitions;
        }
    }
    
//nextValue方法可以理解为是在消息记录中没有指定key的情况下,需要生成一个数用来代替key的hash值
    //方法就是最开始先生成一个随机数,之后在这个随机数的基础上每次请求时均进行+1的操作
 private int nextValue(String topic) {
        AtomicInteger counter = topicCounterMap.get(topic);
        if (null == counter) {
            /*对于每个topic都有一个随机数作为起始的数值,用于计算*/
            counter = new AtomicInteger(ThreadLocalRandom.current().nextInt());
            AtomicInteger currentCounter = topicCounterMap.putIfAbsent(topic, counter);
            if (currentCounter != null) {
                counter = currentCounter;
            }
        }
        //   以原子方式将当前值加 1return counter.getAndIncrement();
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值