You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.3 KiB

  1. package client
  2. import (
  3. "context"
  4. "io"
  5. "time"
  6. "github.com/chrislusf/seaweedfs/weed/pb/messaging_pb"
  7. )
  8. type Subscriber struct {
  9. subscriberClient messaging_pb.SeaweedMessaging_SubscribeClient
  10. }
  11. func (mc *MessagingClient) NewSubscriber(subscriberId, namespace, topic string) (*Subscriber, error) {
  12. stream, err := messaging_pb.NewSeaweedMessagingClient(mc.grpcConnection).Subscribe(context.Background())
  13. if err != nil {
  14. return nil, err
  15. }
  16. // send init message
  17. err = stream.Send(&messaging_pb.SubscriberMessage{
  18. Init: &messaging_pb.SubscriberMessage_InitMessage{
  19. Namespace: namespace,
  20. Topic: topic,
  21. Partition: 0,
  22. StartPosition: messaging_pb.SubscriberMessage_InitMessage_TIMESTAMP,
  23. TimestampNs: time.Now().UnixNano(),
  24. SubscriberId: subscriberId,
  25. },
  26. })
  27. if err != nil {
  28. return nil, err
  29. }
  30. // process init response
  31. initResponse, err := stream.Recv()
  32. if err != nil {
  33. return nil, err
  34. }
  35. if initResponse.Redirect != nil {
  36. // TODO follow redirection
  37. }
  38. return &Subscriber{
  39. subscriberClient: stream,
  40. }, nil
  41. }
  42. func (s *Subscriber) Subscribe(processFn func(m *messaging_pb.Message)) error {
  43. for {
  44. resp, listenErr := s.subscriberClient.Recv()
  45. if listenErr == io.EOF {
  46. return nil
  47. }
  48. if listenErr != nil {
  49. return listenErr
  50. }
  51. processFn(resp.Data)
  52. }
  53. }