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.

96 lines
1.8 KiB

  1. package msgclient
  2. import (
  3. "io"
  4. "log"
  5. "time"
  6. "github.com/chrislusf/seaweedfs/weed/messaging/broker"
  7. "github.com/chrislusf/seaweedfs/weed/pb/messaging_pb"
  8. )
  9. type PubChannel struct {
  10. client messaging_pb.SeaweedMessaging_PublishClient
  11. }
  12. func (mc *MessagingClient) NewPubChannel(chanName string) (*PubChannel, error) {
  13. tp := broker.TopicPartition{
  14. Namespace: "chan",
  15. Topic: chanName,
  16. Partition: 0,
  17. }
  18. grpcConnection, err := mc.findBroker(tp)
  19. if err != nil {
  20. return nil, err
  21. }
  22. pc, err := setupPublisherClient(grpcConnection, tp)
  23. if err != nil {
  24. return nil, err
  25. }
  26. return &PubChannel{
  27. client: pc,
  28. }, nil
  29. }
  30. func (pc *PubChannel) Publish(m []byte) error {
  31. return pc.client.Send(&messaging_pb.PublishRequest{
  32. Data: &messaging_pb.Message{
  33. Value: m,
  34. },
  35. })
  36. }
  37. func (pc *PubChannel) Close() error {
  38. return pc.client.CloseSend()
  39. }
  40. type SubChannel struct {
  41. ch chan []byte
  42. stream messaging_pb.SeaweedMessaging_SubscribeClient
  43. }
  44. func (mc *MessagingClient) NewSubChannel(chanName string) (*SubChannel, error) {
  45. tp := broker.TopicPartition{
  46. Namespace: "chan",
  47. Topic: chanName,
  48. Partition: 0,
  49. }
  50. grpcConnection, err := mc.findBroker(tp)
  51. if err != nil {
  52. return nil, err
  53. }
  54. sc, err := setupSubscriberClient(grpcConnection, "", "chan", chanName, 0, time.Unix(0,0))
  55. if err != nil {
  56. return nil, err
  57. }
  58. t := &SubChannel{
  59. ch: make(chan []byte),
  60. stream: sc,
  61. }
  62. go func() {
  63. for {
  64. resp, subErr := t.stream.Recv()
  65. if subErr == io.EOF {
  66. return
  67. }
  68. if subErr != nil {
  69. log.Printf("fail to receive from netchan %s: %v", chanName, subErr)
  70. return
  71. }
  72. if resp.IsClose {
  73. close(t.ch)
  74. return
  75. }
  76. if resp.Data != nil {
  77. t.ch <- resp.Data.Value
  78. }
  79. }
  80. }()
  81. return t, nil
  82. }
  83. func (sc *SubChannel) Channel() chan []byte {
  84. return sc.ch
  85. }