mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2024-01-19 02:48:24 +00:00
add subscriber api
This commit is contained in:
parent
767f14dfcd
commit
788578d4ea
|
@ -1,14 +1,65 @@
|
||||||
package client
|
package client
|
||||||
|
|
||||||
import "github.com/chrislusf/seaweedfs/weed/pb/messaging_pb"
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/chrislusf/seaweedfs/weed/pb/messaging_pb"
|
||||||
|
)
|
||||||
|
|
||||||
type Subscriber struct {
|
type Subscriber struct {
|
||||||
|
subscriberClient messaging_pb.SeaweedMessaging_SubscribeClient
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *MessagingClient) NewSubscriber(namespace, topic string) *Subscriber {
|
func (mc *MessagingClient) NewSubscriber(subscriberId, namespace, topic string) (*Subscriber, error) {
|
||||||
return &Subscriber{}
|
stream, err := messaging_pb.NewSeaweedMessagingClient(mc.grpcConnection).Subscribe(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// send init message
|
||||||
|
err = stream.Send(&messaging_pb.SubscriberMessage{
|
||||||
|
Init: &messaging_pb.SubscriberMessage_InitMessage{
|
||||||
|
Namespace: namespace,
|
||||||
|
Topic: topic,
|
||||||
|
Partition: 0,
|
||||||
|
StartPosition: messaging_pb.SubscriberMessage_InitMessage_TIMESTAMP,
|
||||||
|
TimestampNs: time.Now().UnixNano(),
|
||||||
|
SubscriberId: subscriberId,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// process init response
|
||||||
|
initResponse, err := stream.Recv()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if initResponse.Redirect != nil {
|
||||||
|
// TODO follow redirection
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Subscriber{
|
||||||
|
subscriberClient: stream,
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Subscriber) Subscribe(processFn func(m *messaging_pb.Message)) error{
|
func (s *Subscriber) Subscribe(processFn func(m *messaging_pb.Message)) error {
|
||||||
|
for {
|
||||||
|
resp, listenErr := s.subscriberClient.Recv()
|
||||||
|
if listenErr == io.EOF {
|
||||||
return nil
|
return nil
|
||||||
|
}
|
||||||
|
if listenErr != nil {
|
||||||
|
return listenErr
|
||||||
|
}
|
||||||
|
processFn(resp.Data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Subscriber) Shutdown() {
|
||||||
|
s.subscriberClient.CloseSend()
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue