kafka producer 中partition 使用方式

     为了更好的实现负载均衡和消息的顺序性,kafka的producer在分发消息时可以通过分发策略发送给指定的partition。实现分发的程序是需要制定消息的key值,而kafka通过key进行策略分发。

     为了更好的弄清楚相关原理,我们从kafka本身提供的分发函数分析:
     源代码如下:    

private[kafka] class DefaultPartitioner[T] extends Partitioner[T] {
  private val random = new java.util.Random
 
  def partition(key: T, numPartitions: Int): Int = {
    if(key == null)
    {
        println("key is null")
        random.nextInt(numPartitions)
    }
    else
    {
        println("key is "+ key + " hashcode is "+key.hashCode)
        math.abs(key.hashCode) % numPartitions
    }
  }
}

       上述类对key进行了模版封装,因此key 可以提供Int,String等类型。
       其中numPartitions是来自ZKBrokerPartitionInfo生成的数据,具体代码是:

val numPartitions = brokerList.map(bid => ZkUtils.readData(zkClient, brokerTopicPath + "/" + bid).toInt)
      (Tips:从上面可以看到,我们可以更多的扩展分区信息,多多利用zookeeper提供的信息,比如sortedBrokerPartitions等等)


        很多时候我们可能要自己实现一个分区函数,具体的使用方式就是:
       

private Properties props = new Properties();

...

 props.put("partitioner.class","***/***/TestPartition");//一定要写对路径和partitioner.class

      具体的实现代码就是改装自DefaultPartitioner的java实现方式,一并贴上:

public class TestPartition implements Partitioner<String>{

	public int partition(String key,int numPartitions)
	{
		//System.out.println("Fuck!!!!");
		System.out.print("partitions number is "+numPartitions+"   ");
		if (key == null) {
			Random random = new Random();
			System.out.println("key is null ");
			return random.nextInt(numPartitions);
		}
		else {
			int result = Math.abs(key.hashCode())%numPartitions; //很奇怪,
                     //hashCode 会生成负数,奇葩,所以加绝对值
			System.out.println("key is "+ key+ " partitions is "+ result);
			return result;
		}
	}
} 
    而发送消息使用方式:

List<String> messages = new java.util.ArrayList<String>();
      String messageString = "test-message"+Integer.toString(messageNo);
      messages.add(messageString);
      //producer.send(new ProducerData<String, String>(topic,"test_key", messageStr));
      ProducerData<String, String> data = new ProducerData<String, String>(topic, messageString, messages);
      producer.send(data);
    kafka官方文档中直接使用
ProducerData<String, String> data = new ProducerData<String, String>(topic, “xxx”, "XXX");
      producer.send(data);
    但是我没有实现,第三个参数用String会报错。

   




    

 

         

 


 


转载于:https://my.oschina.net/u/591402/blog/152837

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值