github.com/openimsdk/tools@v0.0.49/mq/kafka/consumer_group.go (about)

     1  // Copyright © 2023 OpenIM. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package kafka
    16  
    17  import (
    18  	"context"
    19  	"errors"
    20  
    21  	"github.com/IBM/sarama"
    22  	"github.com/openimsdk/tools/log"
    23  )
    24  
    25  type MConsumerGroup struct {
    26  	sarama.ConsumerGroup
    27  	groupID string
    28  	topics  []string
    29  }
    30  
    31  func NewMConsumerGroup(conf *Config, groupID string, topics []string, autoCommitEnable bool) (*MConsumerGroup, error) {
    32  	config, err := BuildConsumerGroupConfig(conf, sarama.OffsetNewest, autoCommitEnable)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  	group, err := NewConsumerGroup(config, conf.Addr, groupID)
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  	return &MConsumerGroup{
    41  		ConsumerGroup: group,
    42  		groupID:       groupID,
    43  		topics:        topics,
    44  	}, nil
    45  }
    46  
    47  func (mc *MConsumerGroup) GetContextFromMsg(cMsg *sarama.ConsumerMessage) context.Context {
    48  	return GetContextWithMQHeader(cMsg.Headers)
    49  }
    50  
    51  func (mc *MConsumerGroup) RegisterHandleAndConsumer(ctx context.Context, handler sarama.ConsumerGroupHandler) {
    52  	for {
    53  		err := mc.ConsumerGroup.Consume(ctx, mc.topics, handler)
    54  		if errors.Is(err, sarama.ErrClosedConsumerGroup) {
    55  			return
    56  		}
    57  		if errors.Is(err, context.Canceled) {
    58  			return
    59  		}
    60  		if err != nil {
    61  			log.ZWarn(ctx, "consume err", err, "topic", mc.topics, "groupID", mc.groupID)
    62  		}
    63  	}
    64  }
    65  
    66  func (mc *MConsumerGroup) Close() error {
    67  	return mc.ConsumerGroup.Close()
    68  }