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/01/06 02:29:27 UTC

[GitHub] [rocketmq-client-go] shendongsd opened a new pull request #768: the first version of high-level-pull-consumer

shendongsd opened a new pull request #768:
URL: https://github.com/apache/rocketmq-client-go/pull/768


   ## What is the purpose of the change
   
   #738 [#738](https://github.com/apache/rocketmq-client-go/issues/738)
   
   ## Brief changelog
   
   the first version of high-level-pull-consumer ,and some functions are not implemented
   
   ## Verifying this change
   
   XXXX
   
   Follow this checklist to help us incorporate your contribution quickly and easily. Notice, `it would be helpful if you could finish the following 5 checklist(the last one is not necessary)before request the community to review your PR`.
   
   - [x] Make sure there is a [Github issue](https://github.com/apache/rocketmq/issues) filed for the change (usually before you start working on it). Trivial changes like typos do not require a Github issue. Your pull request should address just this issue, without pulling in other changes - one PR resolves one issue. 
   - [x] Format the pull request title like `[ISSUE #123] Fix UnknownException when host config not exist`. Each commit in the pull request should have a meaningful subject line and body.
   - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
   - [x] Write necessary unit-test(over 80% coverage) to verify your logic correction, more mock a little better when a cross-module dependency exists.
   - [ ] If this contribution is large, please file an [Apache Individual Contributor License Agreement](http://www.apache.org/licenses/#clas).
   


-- 
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



[GitHub] [rocketmq-client-go] shendongsd commented on pull request #768: the first version of high-level-pull-consumer

Posted by GitBox <gi...@apache.org>.
shendongsd commented on pull request #768:
URL: https://github.com/apache/rocketmq-client-go/pull/768#issuecomment-1073426816


   > fail to run example for `examples/consumer/highlevelpull/main.go`
   > 
   > <img alt="image" width="1452" src="https://user-images.githubusercontent.com/5908412/157888020-52a409ee-9c69-4e3f-9d1f-6993c461ff47.png">
   > 
   > update like bellow would be OK.
   > 
   > <img alt="image" width="695" src="https://user-images.githubusercontent.com/5908412/157888501-ccde76cc-5885-4bea-a13c-a601c4559e75.png">
   
   I have fixed this.


-- 
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



[GitHub] [rocketmq-client-go] francisoliverlee commented on pull request #768: the first version of high-level-pull-consumer

Posted by GitBox <gi...@apache.org>.
francisoliverlee commented on pull request #768:
URL: https://github.com/apache/rocketmq-client-go/pull/768#issuecomment-1065173578


   fail to run example for `examples/consumer/highlevelpull/main.go`
   
   <img width="1452" alt="image" src="https://user-images.githubusercontent.com/5908412/157888020-52a409ee-9c69-4e3f-9d1f-6993c461ff47.png">
   
   
   update like bellow would be OK.
   
   <img width="695" alt="image" src="https://user-images.githubusercontent.com/5908412/157888501-ccde76cc-5885-4bea-a13c-a601c4559e75.png">
   
   


-- 
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



[GitHub] [rocketmq-client-go] yuz10 commented on a change in pull request #768: the first version of high-level-pull-consumer

Posted by GitBox <gi...@apache.org>.
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



[GitHub] [rocketmq-client-go] francisoliverlee commented on pull request #768: the first version of high-level-pull-consumer

Posted by GitBox <gi...@apache.org>.
francisoliverlee commented on pull request #768:
URL: https://github.com/apache/rocketmq-client-go/pull/768#issuecomment-1075869146


   > > fail to run example for `examples/consumer/highlevelpull/main.go`
   > > <img alt="image" width="1452" src="https://user-images.githubusercontent.com/5908412/157888020-52a409ee-9c69-4e3f-9d1f-6993c461ff47.png">
   > > update like bellow would be OK.
   > > <img alt="image" width="695" src="https://user-images.githubusercontent.com/5908412/157888501-ccde76cc-5885-4bea-a13c-a601c4559e75.png">
   > 
   > I have fixed this.
   
   nice!


-- 
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