seaweedfs/weed/mq/msgclient/chan_pub.go

77 lines
1.5 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"
2022-07-02 05:43:25 +00:00
"github.com/chrislusf/seaweedfs/weed/mq/broker"
"github.com/chrislusf/seaweedfs/weed/pb/mq_pb"
2020-05-05 09:05:28 +00:00
)
type PubChannel struct {
2022-07-02 05:43:25 +00:00
client mq_pb.SeaweedMessaging_PublishClient
2020-05-08 09:47:22 +00:00
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 {
2022-07-02 05:43:25 +00:00
err := pc.client.Send(&mq_pb.PublishRequest{
Data: &mq_pb.Message{
2020-05-05 09:05:28 +00:00
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")
2022-07-02 05:43:25 +00:00
if err := pc.client.Send(&mq_pb.PublishRequest{
Data: &mq_pb.Message{
2020-05-08 09:47:22 +00:00
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)
}