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.
gojobs/grpc_cron.go

57 lines
1.3 KiB

2 years ago
package gojobs
2 years ago
import (
2 years ago
"context"
2 years ago
"go.dtapp.net/gojobs/pb"
"google.golang.org/grpc"
2 years ago
"log"
2 years ago
)
// CronConfig 定时任务配置
type CronConfig struct {
Address string // 服务端口 127.0.0.1:8888
}
// Cron 定时任务
type Cron struct {
CronConfig // 配置
Pub pb.PubSubClient // 订阅
Conn *grpc.ClientConn // 链接信息
}
// NewCron 创建定时任务
func NewCron(config *CronConfig) *Cron {
if config.Address == "" {
2 years ago
panic("[定时任务]请填写服务端口")
2 years ago
}
c := &Cron{}
c.Address = config.Address
var err error
// 建立连接 获取client
c.Conn, err = grpc.Dial(c.Address, grpc.WithInsecure())
if err != nil {
2 years ago
panic("[定时任务]{连接失败}" + err.Error())
2 years ago
}
// 新建一个客户端
c.Pub = pb.NewPubSubClient(c.Conn)
return c
}
2 years ago
// Send 发送
2 years ago
func (c *Cron) Send(in *pb.PublishRequest) (*pb.PublishResponse, error) {
2 years ago
log.Printf("[定时任务]{广播开始}编号:%s 类型:%s ip%s\n", in.GetId(), in.GetValue(), in.GetIp())
2 years ago
stream, err := c.Pub.Publish(context.Background(), in)
if err != nil {
2 years ago
log.Printf("[定时任务]{广播失败}编号:%s %v\n", in.GetId(), err)
2 years ago
}
2 years ago
log.Printf("[定时任务]{广播成功}编号:%s 类型:%s ip%s\n", in.GetId(), in.GetValue(), in.GetIp())
2 years ago
return stream, err
}