2 Star 1 Fork 1

mosache/YFrame

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
server.go 1.41 KB
一键复制 编辑 原始数据 按行查看 历史
ヤ沒脩袮兲︶ 提交于 2023-09-12 18:29 . temp
package micro
import (
"context"
"gitee.com/mosache/YFrame/micro/registry"
"google.golang.org/grpc"
"net"
"time"
)
type Server struct {
name string
r registry.Registry
*grpc.Server
registerTimeOut time.Duration
weight uint32 // 权重
group string // group
}
type ServerOpt func(s *Server)
func ServerWithWeight(weight uint32) ServerOpt {
return func(s *Server) {
s.weight = weight
}
}
func ServerWithGroupName(group string) ServerOpt {
return func(s *Server) {
s.group = group
}
}
func ServerWithRegistry(r registry.Registry) ServerOpt {
return func(s *Server) {
s.r = r
}
}
func NewServer(name string, opts ...ServerOpt) *Server {
s := &Server{
name: name,
Server: grpc.NewServer(),
registerTimeOut: time.Second * 3,
}
for _, opt := range opts {
opt(s)
}
return s
}
func (s *Server) Start(addr string) error {
l, err := net.Listen("tcp", addr)
if err != nil {
return err
}
/// 启用注册中心
if s.r != nil {
ctx, cancel := context.WithTimeout(context.Background(), s.registerTimeOut)
defer cancel()
err = s.r.Register(ctx, registry.ServiceInstance{
Name: s.name,
Addr: l.Addr().String(),
Weight: s.weight,
Group: s.group,
})
if err != nil {
return err
}
}
return s.Serve(l)
}
func (s *Server) Close() error {
if s.r != nil {
err := s.r.Close()
if err != nil {
return err
}
}
s.GracefulStop()
return nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/mosache/YFrame.git
git@gitee.com:mosache/YFrame.git
mosache
YFrame
YFrame
v0.1.83

搜索帮助