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.

72 lines
1.3 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(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, "", "chan", chanName, 0, 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.IsClose {
  46. t.stream.Send(&messaging_pb.SubscriberMessage{
  47. IsClose: true,
  48. })
  49. close(t.ch)
  50. return
  51. }
  52. t.ch <- resp.Data.Value
  53. t.md5hash.Write(resp.Data.Value)
  54. }
  55. }()
  56. return t, nil
  57. }
  58. func (sc *SubChannel) Channel() chan []byte {
  59. return sc.ch
  60. }
  61. func (sc *SubChannel) Md5() []byte {
  62. return sc.md5hash.Sum(nil)
  63. }