1 Star 0 Fork 0

fpy-go / plugin

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
notice.go 2.00 KB
一键复制 编辑 原始数据 按行查看 历史
晴空 提交于 2024-01-31 15:19 . 实现Grpc和rpc创建Demo
package module
import (
"fmt"
"gitee.com/fpy-go/plugin/pkg/extend/model"
gplugin "github.com/hashicorp/go-plugin"
"net/rpc"
"os"
"time"
)
var parentPid int
func init() {
parentPid = os.Getppid()
}
// Notice 通知服务插件接口
type Notice interface {
Info() model.PluginInfo
Send(data []byte) model.JsonRes
}
// NoticeRPC 基于RPC实现
type NoticeRPC struct {
Client *rpc.Client
}
func (g *NoticeRPC) Info() model.PluginInfo {
var resp model.PluginInfo
err := g.Client.Call("Plugin.Info", new(interface{}), &resp)
if err != nil {
panic(err)
}
return resp
}
func (g *NoticeRPC) Send(data []byte) model.JsonRes {
var resp model.JsonRes
err := g.Client.Call("Plugin.Send", data, &resp)
if err != nil {
panic(err)
}
return resp
}
// NoticeRPCServer GreeterRPC的RPC服务器,符合 net/rpc的要求
type NoticeRPCServer struct {
Impl Notice
}
func (s *NoticeRPCServer) Info(args interface{}, resp *model.PluginInfo) error {
*resp = s.Impl.Info()
return nil
}
func (s *NoticeRPCServer) Send(data []byte, resp *model.JsonRes) error {
*resp = s.Impl.Send(data)
return nil
}
// NoticePlugin 插件的虚拟实现。用于PluginMap的插件接口。在运行时,来自插件实现的实际实现会覆盖
type NoticePlugin struct{}
// Server 此方法由插件进程延迟的调用
func (NoticePlugin) Server(*gplugin.MuxBroker) (interface{}, error) {
checkParentAlive()
return &NoticeRPCServer{}, nil
}
// Client 此方法由宿主进程调用
func (NoticePlugin) Client(b *gplugin.MuxBroker, c *rpc.Client) (interface{}, error) {
return &NoticeRPC{Client: c}, nil
}
// checkParentAlive 检查父进程(也就是 client )是否退出,如果退出了,自己也需要退出。
func checkParentAlive() {
go func() {
for {
if parentPid == 1 || os.Getppid() != parentPid {
fmt.Println("parent no alive, exit")
os.Exit(0)
}
_, err := os.FindProcess(parentPid)
if err != nil {
fmt.Println("parent no alive, exit")
os.Exit(0)
}
time.Sleep(5 * time.Second)
}
}()
}
1
https://gitee.com/fpy-go/plugin.git
git@gitee.com:fpy-go/plugin.git
fpy-go
plugin
plugin
345896415f40

搜索帮助