jerrypeng commented on a change in pull request #221: Auto update the client to
handle changes in number of partitions
URL: https://github.com/apache/pulsar-client-go/pull/221#discussion_r408421517
##########
File path: pulsar/consumer_impl.go
##########
@@ -130,56 +136,108 @@ func internalTopicSubscribe(client *client, options
ConsumerOptions, topic strin
log: log.WithField("topic", topic),
}
- partitions, err := client.TopicPartitions(topic)
+ if options.Name != "" {
+ consumer.consumerName = options.Name
+ } else {
+ consumer.consumerName = generateRandomName()
+ }
+
+ err := consumer.internalTopicSubscribeToPartitions()
if err != nil {
return nil, err
}
- numPartitions := len(partitions)
- consumer.consumers = make([]*partitionConsumer, numPartitions)
+ // set up timer to monitor for new partitions being added
+ duration := options.AutoDiscoveryPeriod
+ if duration <= 0 {
+ duration = defaultAutoDiscoveryDuration
+ }
+ consumer.ticker = time.NewTicker(duration)
+
+ go func() {
+ for range consumer.ticker.C {
+ consumer.log.Debug("Auto discovering new partitions")
+ consumer.internalTopicSubscribeToPartitions()
+ }
+ }()
+
+ return consumer, nil
+}
+
+func (c *consumer) internalTopicSubscribeToPartitions() error {
+ partitions, err := c.client.TopicPartitions(c.topic)
+ if err != nil {
+ return err
+ }
+
+ oldNumPartitions := 0
+ newNumPartitions := len(partitions)
+
+ c.Lock()
+ oldConsumers := c.consumers
+ c.Unlock()
+
+ if oldConsumers != nil {
+ oldNumPartitions = len(oldConsumers)
+ if oldNumPartitions == newNumPartitions {
+ c.log.Debug("Number of partitions in topic has not
changed")
+ return nil
+ }
+
+ c.log.WithField("old_partitions", oldNumPartitions).
+ WithField("new_partitions", newNumPartitions).
+ Info("Changed number of partitions in topic")
+ }
+
+ consumers := make([]*partitionConsumer, newNumPartitions)
+
+ // Copy over the existing consumer instances
+ for i := 0; i < oldNumPartitions; i++ {
Review comment:
Why isn't there a mutex here when we are setting new consumers to old
consumers? Shouldn't this whole block be in a mutux to prevent race conditions?
https://github.com/apache/pulsar-client-go/pull/221/files#diff-8b65201e8d71d0f36fdcbdfc7b5d5f0aR176-R197
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
With regards,
Apache Git Services