You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@rocketmq.apache.org by GitBox <gi...@apache.org> on 2022/04/02 03:11:34 UTC
[GitHub] [rocketmq-client-go] yuz10 commented on a change in pull request #768: the first version of high-level-pull-consumer
yuz10 commented on a change in pull request #768:
URL: https://github.com/apache/rocketmq-client-go/pull/768#discussion_r840999338
##########
File path: consumer/high_level_pull_consumer.go
##########
@@ -0,0 +1,481 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package consumer
+
+import (
+ "context"
+ "fmt"
+ errors2 "github.com/apache/rocketmq-client-go/v2/errors"
+ "github.com/apache/rocketmq-client-go/v2/internal"
+ "github.com/apache/rocketmq-client-go/v2/primitive"
+ "github.com/apache/rocketmq-client-go/v2/rlog"
+ "github.com/pkg/errors"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+type defaultHighLevelPullConsumer struct {
+ *defaultManualPullConsumer
+ consumerGroup string
+ model MessageModel
+ namesrv internal.Namesrvs
+ option consumerOptions
+ client internal.RMQClient
+ interceptor primitive.Interceptor
+ pullFromWhichNodeTable sync.Map
+ storage OffsetStore
+ cType ConsumeType
+ state int32
+ subscriptionDataTable sync.Map
+ allocate func(string, string, []*primitive.MessageQueue, []string) []*primitive.MessageQueue
+ once sync.Once
+ unitMode bool
+ topicSubscribeInfoTable sync.Map
+ subscribedTopic map[string]string
+ closeOnce sync.Once
+ done chan struct{}
+ consumerStartTimestamp int64
+ processQueueTable sync.Map
+ fromWhere ConsumeFromWhere
+ stat *StatsManager
+ consumerMap sync.Map
+}
+
+func NewHighLevelPullConsumer(options ...Option) (*defaultHighLevelPullConsumer, error) {
+ defaultOpts := defaultHighLevelPullConsumerOptions()
+ for _, apply := range options {
+ apply(&defaultOpts)
+ }
+
+ srvs, err := internal.NewNamesrv(defaultOpts.Resolver)
+ if err != nil {
+ return nil, errors.Wrap(err, "new Namesrv failed.")
+ }
+
+ defaultOpts.Namesrv = srvs
+
+ if defaultOpts.Namespace != "" {
+ defaultOpts.GroupName = defaultOpts.Namespace + "%" + defaultOpts.GroupName
+ }
+
+ dc := &defaultManualPullConsumer{
+ client: internal.GetOrNewRocketMQClient(defaultOpts.ClientOptions, nil),
+ option: defaultOpts,
+ namesrv: srvs,
+ }
+
+ hpc := &defaultHighLevelPullConsumer{
+ client: internal.GetOrNewRocketMQClient(defaultOpts.ClientOptions, nil),
+ consumerGroup: defaultOpts.GroupName,
+ defaultManualPullConsumer: dc,
+ cType: _PullConsume,
+ state: int32(internal.StateCreateJust),
+ model: defaultOpts.ConsumerModel,
+ allocate: defaultOpts.Strategy,
+ namesrv: srvs,
+ option: defaultOpts,
+ subscribedTopic: make(map[string]string, 0),
+ done: make(chan struct{}, 1),
+ }
+ hpc.option.ClientOptions.Namesrv, err = internal.GetNamesrv(hpc.client.ClientID())
+ if err != nil {
+ return nil, err
+ }
+ hpc.namesrv = hpc.option.ClientOptions.Namesrv
+ hpc.interceptor = primitive.ChainInterceptors(hpc.option.Interceptors...)
+
+ if hpc.model == Clustering {
+ retryTopic := internal.GetRetryTopic(hpc.consumerGroup)
+ sub := buildSubscriptionData(retryTopic, MessageSelector{TAG, _SubAll})
+ hpc.subscriptionDataTable.Store(retryTopic, sub)
+ }
+ return hpc, nil
+}
+
+func (hpc *defaultHighLevelPullConsumer) Start() error {
+ atomic.StoreInt32(&hpc.state, int32(internal.StateRunning))
+
+ var err error
+ hpc.once.Do(func() {
+ rlog.Info("the consumer start beginning", map[string]interface{}{
+ rlog.LogKeyConsumerGroup: hpc.consumerGroup,
+ "messageModel": hpc.model,
+ "unitMode": hpc.unitMode,
+ })
+ atomic.StoreInt32(&hpc.state, int32(internal.StateStartFailed))
+ hpc.validate()
+
+ err = hpc.RegisterConsumer(hpc.consumerGroup, hpc)
+ if err != nil {
+ rlog.Error("the consumer group has been created, specify another one", map[string]interface{}{
+ rlog.LogKeyConsumerGroup: hpc.consumerGroup,
+ })
+ err = errors2.ErrCreated
+ return
+ }
+
+ if hpc.model == Clustering {
+ // set retry topic
+ retryTopic := internal.GetRetryTopic(hpc.consumerGroup)
+ sub := buildSubscriptionData(retryTopic, MessageSelector{TAG, _SubAll})
+ hpc.subscriptionDataTable.Store(retryTopic, sub)
+ }
+
+ if hpc.model == Clustering {
+ hpc.option.ChangeInstanceNameToPID()
+ hpc.storage = NewRemoteOffsetStore(hpc.consumerGroup, hpc.client, hpc.namesrv)
+ } else {
+ hpc.storage = NewLocalFileOffsetStore(hpc.consumerGroup, hpc.client.ClientID())
+ }
+
+ hpc.client.Start()
+ atomic.StoreInt32(&hpc.state, int32(internal.StateRunning))
+ hpc.consumerStartTimestamp = time.Now().UnixNano() / int64(time.Millisecond)
+ if err != nil {
+ return
+ }
+ })
+ if err != nil {
+ return err
+ }
+
+ hpc.client.UpdateTopicRouteInfo()
+ for k := range hpc.subscribedTopic {
+ _, exist := hpc.topicSubscribeInfoTable.Load(k)
+ if !exist {
+ hpc.client.Shutdown()
+ return fmt.Errorf("the topic=%s route info not found, it may not exist", k)
+ }
+ }
+ hpc.client.SendHeartbeatToAllBrokerWithLock()
+ hpc.Rebalance()
+ return err
+}
+
+func (hpc *defaultHighLevelPullConsumer) Shutdown() error {
+ var err error
+ hpc.closeOnce.Do(func() {
+ close(hpc.done)
+ hpc.UnregisterConsumer(hpc.consumerGroup)
+ atomic.StoreInt32(&hpc.state, int32(internal.StateShutdown))
+ mqs := make([]*primitive.MessageQueue, 0)
+ hpc.processQueueTable.Range(func(key, value interface{}) bool {
+ k := key.(primitive.MessageQueue)
+ pq := value.(*processQueue)
+ pq.WithDropped(true)
+ // close msg channel using RWMutex to make sure no data was writing
+ pq.mutex.Lock()
+ close(pq.msgCh)
+ pq.mutex.Unlock()
+ mqs = append(mqs, &k)
+ return true
+ })
+ hpc.storage.persist(mqs)
+ hpc.client.Shutdown()
+ })
+ return err
+}
+
+func (hpc *defaultHighLevelPullConsumer) Subscribe(topic string, selector MessageSelector) error {
+ if atomic.LoadInt32(&hpc.state) == int32(internal.StateStartFailed) ||
+ atomic.LoadInt32(&hpc.state) == int32(internal.StateShutdown) {
+ return errors2.ErrStartTopic
+ }
+
+ if "" == topic {
+ rlog.Error(fmt.Sprintf("topic is null"), nil)
+ }
+
+ if hpc.option.Namespace != "" {
+ topic = hpc.option.Namespace + "%" + topic
+ }
+ data := buildSubscriptionData(topic, selector)
+ hpc.subscriptionDataTable.Store(topic, data)
+ hpc.subscribedTopic[topic] = ""
+ routeData, _, err := hpc.namesrv.UpdateTopicRouteInfo(topic)
+ if err == nil {
+ hpc.topicSubscribeInfoTable.Store(topic, routeData)
+ }
+ hpc.Rebalance()
+ return nil
+}
+
+func (hpc *defaultHighLevelPullConsumer) Unsubscribe(topic string) error {
+ if hpc.option.Namespace != "" {
+ topic = hpc.option.Namespace + "%" + topic
+ }
+
+ if "" == topic {
+ rlog.Error(fmt.Sprintf("topic is null"), nil)
+ }
+
+ hpc.subscriptionDataTable.Delete(topic)
+ return nil
+}
+
+func (hpc *defaultHighLevelPullConsumer) Pull(ctx context.Context, topic string, numbers int) (*primitive.PullResult, error) {
+ queue, err := hpc.getNextQueueOf(topic)
Review comment:
send a message to the topic can not be consumed immediatly, If the topic have 10 queues, we have to wait for 180 seconds, because no message is in other 9 queues, and each queue will wait for _BrokerSuspendMaxTime(20 seconds)
##########
File path: consumer/high_level_pull_consumer.go
##########
@@ -0,0 +1,481 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package consumer
+
+import (
+ "context"
+ "fmt"
+ errors2 "github.com/apache/rocketmq-client-go/v2/errors"
+ "github.com/apache/rocketmq-client-go/v2/internal"
+ "github.com/apache/rocketmq-client-go/v2/primitive"
+ "github.com/apache/rocketmq-client-go/v2/rlog"
+ "github.com/pkg/errors"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+type defaultHighLevelPullConsumer struct {
+ *defaultManualPullConsumer
+ consumerGroup string
+ model MessageModel
+ namesrv internal.Namesrvs
+ option consumerOptions
+ client internal.RMQClient
+ interceptor primitive.Interceptor
+ pullFromWhichNodeTable sync.Map
+ storage OffsetStore
+ cType ConsumeType
+ state int32
+ subscriptionDataTable sync.Map
+ allocate func(string, string, []*primitive.MessageQueue, []string) []*primitive.MessageQueue
+ once sync.Once
+ unitMode bool
+ topicSubscribeInfoTable sync.Map
+ subscribedTopic map[string]string
+ closeOnce sync.Once
+ done chan struct{}
+ consumerStartTimestamp int64
+ processQueueTable sync.Map
+ fromWhere ConsumeFromWhere
+ stat *StatsManager
+ consumerMap sync.Map
+}
+
+func NewHighLevelPullConsumer(options ...Option) (*defaultHighLevelPullConsumer, error) {
+ defaultOpts := defaultHighLevelPullConsumerOptions()
+ for _, apply := range options {
+ apply(&defaultOpts)
+ }
+
+ srvs, err := internal.NewNamesrv(defaultOpts.Resolver)
+ if err != nil {
+ return nil, errors.Wrap(err, "new Namesrv failed.")
+ }
+
+ defaultOpts.Namesrv = srvs
+
+ if defaultOpts.Namespace != "" {
+ defaultOpts.GroupName = defaultOpts.Namespace + "%" + defaultOpts.GroupName
+ }
+
+ dc := &defaultManualPullConsumer{
+ client: internal.GetOrNewRocketMQClient(defaultOpts.ClientOptions, nil),
+ option: defaultOpts,
+ namesrv: srvs,
+ }
+
+ hpc := &defaultHighLevelPullConsumer{
+ client: internal.GetOrNewRocketMQClient(defaultOpts.ClientOptions, nil),
+ consumerGroup: defaultOpts.GroupName,
+ defaultManualPullConsumer: dc,
+ cType: _PullConsume,
+ state: int32(internal.StateCreateJust),
+ model: defaultOpts.ConsumerModel,
+ allocate: defaultOpts.Strategy,
+ namesrv: srvs,
+ option: defaultOpts,
+ subscribedTopic: make(map[string]string, 0),
+ done: make(chan struct{}, 1),
+ }
+ hpc.option.ClientOptions.Namesrv, err = internal.GetNamesrv(hpc.client.ClientID())
+ if err != nil {
+ return nil, err
+ }
+ hpc.namesrv = hpc.option.ClientOptions.Namesrv
+ hpc.interceptor = primitive.ChainInterceptors(hpc.option.Interceptors...)
+
+ if hpc.model == Clustering {
+ retryTopic := internal.GetRetryTopic(hpc.consumerGroup)
+ sub := buildSubscriptionData(retryTopic, MessageSelector{TAG, _SubAll})
+ hpc.subscriptionDataTable.Store(retryTopic, sub)
+ }
+ return hpc, nil
+}
+
+func (hpc *defaultHighLevelPullConsumer) Start() error {
+ atomic.StoreInt32(&hpc.state, int32(internal.StateRunning))
+
+ var err error
+ hpc.once.Do(func() {
+ rlog.Info("the consumer start beginning", map[string]interface{}{
+ rlog.LogKeyConsumerGroup: hpc.consumerGroup,
+ "messageModel": hpc.model,
+ "unitMode": hpc.unitMode,
+ })
+ atomic.StoreInt32(&hpc.state, int32(internal.StateStartFailed))
+ hpc.validate()
+
+ err = hpc.RegisterConsumer(hpc.consumerGroup, hpc)
+ if err != nil {
+ rlog.Error("the consumer group has been created, specify another one", map[string]interface{}{
+ rlog.LogKeyConsumerGroup: hpc.consumerGroup,
+ })
+ err = errors2.ErrCreated
+ return
+ }
+
+ if hpc.model == Clustering {
+ // set retry topic
+ retryTopic := internal.GetRetryTopic(hpc.consumerGroup)
+ sub := buildSubscriptionData(retryTopic, MessageSelector{TAG, _SubAll})
+ hpc.subscriptionDataTable.Store(retryTopic, sub)
+ }
+
+ if hpc.model == Clustering {
+ hpc.option.ChangeInstanceNameToPID()
+ hpc.storage = NewRemoteOffsetStore(hpc.consumerGroup, hpc.client, hpc.namesrv)
+ } else {
+ hpc.storage = NewLocalFileOffsetStore(hpc.consumerGroup, hpc.client.ClientID())
+ }
+
+ hpc.client.Start()
+ atomic.StoreInt32(&hpc.state, int32(internal.StateRunning))
+ hpc.consumerStartTimestamp = time.Now().UnixNano() / int64(time.Millisecond)
+ if err != nil {
+ return
+ }
+ })
+ if err != nil {
+ return err
+ }
+
+ hpc.client.UpdateTopicRouteInfo()
+ for k := range hpc.subscribedTopic {
+ _, exist := hpc.topicSubscribeInfoTable.Load(k)
+ if !exist {
+ hpc.client.Shutdown()
+ return fmt.Errorf("the topic=%s route info not found, it may not exist", k)
+ }
+ }
+ hpc.client.SendHeartbeatToAllBrokerWithLock()
+ hpc.Rebalance()
+ return err
+}
+
+func (hpc *defaultHighLevelPullConsumer) Shutdown() error {
+ var err error
+ hpc.closeOnce.Do(func() {
+ close(hpc.done)
+ hpc.UnregisterConsumer(hpc.consumerGroup)
+ atomic.StoreInt32(&hpc.state, int32(internal.StateShutdown))
+ mqs := make([]*primitive.MessageQueue, 0)
+ hpc.processQueueTable.Range(func(key, value interface{}) bool {
+ k := key.(primitive.MessageQueue)
+ pq := value.(*processQueue)
+ pq.WithDropped(true)
+ // close msg channel using RWMutex to make sure no data was writing
+ pq.mutex.Lock()
+ close(pq.msgCh)
+ pq.mutex.Unlock()
+ mqs = append(mqs, &k)
+ return true
+ })
+ hpc.storage.persist(mqs)
+ hpc.client.Shutdown()
+ })
+ return err
+}
+
+func (hpc *defaultHighLevelPullConsumer) Subscribe(topic string, selector MessageSelector) error {
+ if atomic.LoadInt32(&hpc.state) == int32(internal.StateStartFailed) ||
+ atomic.LoadInt32(&hpc.state) == int32(internal.StateShutdown) {
+ return errors2.ErrStartTopic
+ }
+
+ if "" == topic {
+ rlog.Error(fmt.Sprintf("topic is null"), nil)
+ }
+
+ if hpc.option.Namespace != "" {
+ topic = hpc.option.Namespace + "%" + topic
+ }
+ data := buildSubscriptionData(topic, selector)
+ hpc.subscriptionDataTable.Store(topic, data)
+ hpc.subscribedTopic[topic] = ""
+ routeData, _, err := hpc.namesrv.UpdateTopicRouteInfo(topic)
+ if err == nil {
+ hpc.topicSubscribeInfoTable.Store(topic, routeData)
+ }
+ hpc.Rebalance()
+ return nil
+}
+
+func (hpc *defaultHighLevelPullConsumer) Unsubscribe(topic string) error {
+ if hpc.option.Namespace != "" {
+ topic = hpc.option.Namespace + "%" + topic
+ }
+
+ if "" == topic {
+ rlog.Error(fmt.Sprintf("topic is null"), nil)
+ }
+
+ hpc.subscriptionDataTable.Delete(topic)
+ return nil
+}
+
+func (hpc *defaultHighLevelPullConsumer) Pull(ctx context.Context, topic string, numbers int) (*primitive.PullResult, error) {
+ queue, err := hpc.getNextQueueOf(topic)
Review comment:
No rebalance, two consumers in the same group will receive a message twice.
--
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.
To unsubscribe, e-mail: dev-unsubscribe@rocketmq.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org