kafka producer 中partition 使用方式
来源:互联网 发布:mac照片分类 编辑:程序博客网 时间:2024/06/06 21:42
为了更好的实现负载均衡和消息的顺序性,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会报错。
0 0
- kafka producer 中partition 使用方式
- kafka Producer API使用
- 使用启动kafka中producer出现UnrecognizedOptionException错误
- Kafka Producer
- kafka producer
- kafka--producer
- kafka新的producer api使用
- 更加深入剖析Kafka--Producer篇(中)
- Kafka的Producer和Consumer的示例(使用java语言)
- Kafka的Producer和Consumer的示例(使用java语言)
- Kafka使用Java进行Producer和Consumer编程
- kafka producer的serializer
- kafka producer总结
- Kafka Producer APIs
- Kafka Producer接口
- kafka的producer测试
- kafka producer demo 生产者
- [Apache Kafka]开发producer
- 第8章,数据类型
- java用PrepareStatement实现多sql语句执行
- Block 的 使用
- 第9章,字符集
- Libevent源码学习(二) 事件的概念
- kafka producer 中partition 使用方式
- Java中Collection和Collections的区别
- 开发我过去常认为那些属于未来的东西
- URL的井号
- 第10章 索引
- [books] - SICP 2nd edition
- 第11章 视图
- 拦截所有push进来的控制器
- 第12章 存储过程和函数