seaweedfs/weed/mq/client/sub_client/subscribe.go

73 lines
2.1 KiB
Go
Raw Normal View History

2023-08-29 00:02:12 +08:00
package sub_client
import (
2023-09-01 15:36:51 +08:00
"context"
"fmt"
"github.com/seaweedfs/seaweedfs/weed/pb"
2023-08-29 00:02:12 +08:00
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
2023-09-01 15:36:51 +08:00
"sync"
2023-08-29 00:02:12 +08:00
)
2023-09-05 12:43:50 +08:00
// Subscribe subscribes to a topic's specified partitions.
// If a partition is moved to another broker, the subscriber will automatically reconnect to the new broker.
2023-08-29 00:02:12 +08:00
2023-09-05 12:43:50 +08:00
func (sub *TopicSubscriber) Subscribe() error {
2023-09-01 15:36:51 +08:00
var wg sync.WaitGroup
for _, brokerPartitionAssignment := range sub.brokerPartitionAssignments {
brokerAddress := brokerPartitionAssignment.LeaderBroker
2023-09-05 12:43:50 +08:00
grpcConnection, err := pb.GrpcDial(context.Background(), brokerAddress, true, sub.SubscriberConfig.GrpcDialOption)
2023-09-01 15:36:51 +08:00
if err != nil {
return fmt.Errorf("dial broker %s: %v", brokerAddress, err)
}
brokerClient := mq_pb.NewSeaweedMessagingClient(grpcConnection)
subscribeClient, err := brokerClient.Subscribe(context.Background(), &mq_pb.SubscribeRequest{
Consumer: &mq_pb.SubscribeRequest_Consumer{
2023-09-05 12:43:50 +08:00
ConsumerGroup: sub.SubscriberConfig.GroupId,
ConsumerId: sub.SubscriberConfig.GroupInstanceId,
2023-09-01 15:36:51 +08:00
},
Cursor: &mq_pb.SubscribeRequest_Cursor{
Topic: &mq_pb.Topic{
2023-09-05 12:43:50 +08:00
Namespace: sub.ContentConfig.Namespace,
Name: sub.ContentConfig.Topic,
2023-09-01 15:36:51 +08:00
},
Partition: &mq_pb.Partition{
RingSize: brokerPartitionAssignment.Partition.RingSize,
RangeStart: brokerPartitionAssignment.Partition.RangeStart,
RangeStop: brokerPartitionAssignment.Partition.RangeStop,
},
2023-09-05 12:43:50 +08:00
Filter: sub.ContentConfig.Filter,
2023-09-01 15:36:51 +08:00
},
})
if err != nil {
return fmt.Errorf("create subscribe client: %v", err)
}
wg.Add(1)
go func() {
defer wg.Done()
2023-09-05 12:43:50 +08:00
if sub.OnCompletionFunc != nil {
defer sub.OnCompletionFunc()
2023-09-01 15:36:51 +08:00
}
for {
resp, err := subscribeClient.Recv()
if err != nil {
fmt.Printf("subscribe error: %v\n", err)
return
}
if resp.Message == nil {
continue
}
switch m := resp.Message.(type) {
case *mq_pb.SubscribeResponse_Data:
2023-09-05 12:43:50 +08:00
if !sub.OnEachMessageFunc(m.Data.Key, m.Data.Value) {
2023-09-01 15:36:51 +08:00
return
}
case *mq_pb.SubscribeResponse_Ctrl:
// ignore
}
}
}()
2023-08-29 00:02:12 +08:00
}
2023-09-01 15:36:51 +08:00
wg.Wait()
return nil
2023-08-29 00:02:12 +08:00
}