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.

76 lines
1.4 KiB

5 years ago
5 years ago
5 years ago
5 years ago
  1. package msgclient
  2. import (
  3. "crypto/md5"
  4. "hash"
  5. "io"
  6. "log"
  7. "time"
  8. "github.com/chrislusf/seaweedfs/weed/messaging/broker"
  9. "github.com/chrislusf/seaweedfs/weed/pb/messaging_pb"
  10. )
  11. type SubChannel struct {
  12. ch chan []byte
  13. stream messaging_pb.SeaweedMessaging_SubscribeClient
  14. md5hash hash.Hash
  15. }
  16. func (mc *MessagingClient) NewSubChannel(subscriberId, chanName string) (*SubChannel, error) {
  17. tp := broker.TopicPartition{
  18. Namespace: "chan",
  19. Topic: chanName,
  20. Partition: 0,
  21. }
  22. grpcConnection, err := mc.findBroker(tp)
  23. if err != nil {
  24. return nil, err
  25. }
  26. sc, err := setupSubscriberClient(grpcConnection, tp, subscriberId, time.Unix(0, 0))
  27. if err != nil {
  28. return nil, err
  29. }
  30. t := &SubChannel{
  31. ch: make(chan []byte),
  32. stream: sc,
  33. md5hash: md5.New(),
  34. }
  35. go func() {
  36. for {
  37. resp, subErr := t.stream.Recv()
  38. if subErr == io.EOF {
  39. return
  40. }
  41. if subErr != nil {
  42. log.Printf("fail to receive from netchan %s: %v", chanName, subErr)
  43. return
  44. }
  45. if resp.Data == nil {
  46. // this could be heartbeat from broker
  47. continue
  48. }
  49. if resp.Data.IsClose {
  50. t.stream.Send(&messaging_pb.SubscriberMessage{
  51. IsClose: true,
  52. })
  53. close(t.ch)
  54. return
  55. }
  56. t.ch <- resp.Data.Value
  57. t.md5hash.Write(resp.Data.Value)
  58. }
  59. }()
  60. return t, nil
  61. }
  62. func (sc *SubChannel) Channel() chan []byte {
  63. return sc.ch
  64. }
  65. func (sc *SubChannel) Md5() []byte {
  66. return sc.md5hash.Sum(nil)
  67. }