seaweedfs/weed/messaging/msgclient/chan_pub.go

77 lines
1.6 KiB
Go
Raw Normal View History

2020-05-05 09:05:28 +00:00
package msgclient
import (
2020-05-09 07:43:53 +00:00
"crypto/md5"
"hash"
2020-05-05 09:05:28 +00:00
"io"
"log"
2020-05-08 09:47:22 +00:00
"google.golang.org/grpc"
2020-05-05 09:05:28 +00:00
"github.com/chrislusf/seaweedfs/weed/messaging/broker"
"github.com/chrislusf/seaweedfs/weed/pb/messaging_pb"
)
type PubChannel struct {
2020-05-08 09:47:22 +00:00
client messaging_pb.SeaweedMessaging_PublishClient
grpcConnection *grpc.ClientConn
2020-05-09 07:43:53 +00:00
md5hash hash.Hash
2020-05-05 09:05:28 +00:00
}
func (mc *MessagingClient) NewPubChannel(chanName string) (*PubChannel, error) {
tp := broker.TopicPartition{
Namespace: "chan",
Topic: chanName,
Partition: 0,
}
grpcConnection, err := mc.findBroker(tp)
if err != nil {
return nil, err
}
pc, err := setupPublisherClient(grpcConnection, tp)
if err != nil {
return nil, err
}
return &PubChannel{
2020-05-08 09:47:22 +00:00
client: pc,
grpcConnection: grpcConnection,
2020-05-09 07:43:53 +00:00
md5hash: md5.New(),
2020-05-05 09:05:28 +00:00
}, nil
}
func (pc *PubChannel) Publish(m []byte) error {
2020-05-09 07:43:53 +00:00
err := pc.client.Send(&messaging_pb.PublishRequest{
2020-05-05 09:05:28 +00:00
Data: &messaging_pb.Message{
Value: m,
},
})
2020-05-09 07:43:53 +00:00
if err == nil {
pc.md5hash.Write(m)
}
return err
2020-05-05 09:05:28 +00:00
}
func (pc *PubChannel) Close() error {
2020-05-08 09:47:22 +00:00
// println("send closing")
if err := pc.client.Send(&messaging_pb.PublishRequest{
Data: &messaging_pb.Message{
IsClose: true,
},
}); err != nil {
log.Printf("err send close: %v", err)
}
// println("receive closing")
if _, err := pc.client.Recv(); err != nil && err != io.EOF {
log.Printf("err receive close: %v", err)
}
// println("close connection")
if err := pc.grpcConnection.Close(); err != nil {
log.Printf("err connection close: %v", err)
}
return nil
2020-05-05 09:05:28 +00:00
}
2020-05-09 07:43:53 +00:00
func (pc *PubChannel) Md5() []byte {
return pc.md5hash.Sum(nil)
}