diff options
author | Mahendra M <mahendra.m@gmail.com> | 2013-06-25 12:42:22 +0530 |
---|---|---|
committer | Mahendra M <mahendra.m@gmail.com> | 2013-06-25 12:42:22 +0530 |
commit | 119d4114f9ddb909b2147e75006da6ac13ad3ed8 (patch) | |
tree | 79f237efd502c10d618b40c68e7d56963c9130aa /kafka/partitioner.py | |
parent | 28884c80f3cea53220c77a4b648488442e3900dd (diff) | |
parent | 883eed1f8ce1af37c621ad6ec89dc993694fd29b (diff) | |
download | kafka-python-119d4114f9ddb909b2147e75006da6ac13ad3ed8.tar.gz |
Merge branch 'master' into lazythread
Diffstat (limited to 'kafka/partitioner.py')
-rw-r--r-- | kafka/partitioner.py | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/kafka/partitioner.py b/kafka/partitioner.py new file mode 100644 index 0000000..84db4d5 --- /dev/null +++ b/kafka/partitioner.py @@ -0,0 +1,56 @@ +from itertools import cycle + + +class Partitioner(object): + """ + Base class for a partitioner + """ + def __init__(self, partitions): + """ + Initialize the partitioner + + partitions - A list of available partitions (during startup) + """ + self.partitions = partitions + + def partition(self, key, partitions): + """ + Takes a string key and num_partitions as argument and returns + a partition to be used for the message + + partitions - The list of partitions is passed in every call. This + may look like an overhead, but it will be useful + (in future) when we handle cases like rebalancing + """ + raise NotImplemented('partition function has to be implemented') + + +class RoundRobinPartitioner(Partitioner): + """ + Implements a round robin partitioner which sends data to partitions + in a round robin fashion + """ + def __init__(self, partitions): + self._set_partitions(partitions) + + def _set_partitions(self, partitions): + self.partitions = partitions + self.iterpart = cycle(partitions) + + def partition(self, key, partitions): + # Refresh the partition list if necessary + if self.partitions != partitions: + self._set_partitions(partitions) + + return self.iterpart.next() + + +class HashedPartitioner(Partitioner): + """ + Implements a partitioner which selects the target partition based on + the hash of the key + """ + def partition(self, key, partitions): + size = len(partitions) + idx = hash(key) % size + return partitions[idx] |