95 lines
2.0 KiB
Go
95 lines
2.0 KiB
Go
package service
|
|
|
|
import (
|
|
"common/discover"
|
|
"common/discover/common"
|
|
"common/log"
|
|
"common/utils"
|
|
"context"
|
|
"fmt"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/keepalive"
|
|
"os"
|
|
"strconv"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type IService interface {
|
|
Init(addr string)
|
|
Close()
|
|
}
|
|
|
|
type ServiceBase struct {
|
|
Target string
|
|
SID string
|
|
Serve *grpc.Server
|
|
EtcdTTL int64
|
|
OnInit func(serve *grpc.Server)
|
|
OnClose func()
|
|
|
|
wg *sync.WaitGroup
|
|
}
|
|
|
|
func (s *ServiceBase) Init(addr string) {
|
|
s.wg = &sync.WaitGroup{}
|
|
s.wg.Add(1)
|
|
s.SID = utils.SnowflakeInstance().Generate().String()
|
|
go func() {
|
|
defer s.wg.Done()
|
|
defer s.OnClose()
|
|
defer discover.UnRegisterGrpcServer(s.SID)
|
|
|
|
pMin, _ := strconv.ParseInt(os.Getenv("P_MIN"), 10, 64)
|
|
pMax, _ := strconv.ParseInt(os.Getenv("P_MAX"), 10, 64)
|
|
if pMin == 0 || pMax == 0 || pMin > pMax {
|
|
log.Errorf(" %v init err: pMin or pMax is 0 or pMin > pMax", s.Target)
|
|
return
|
|
}
|
|
|
|
// 服务注册
|
|
lis, port, err := common.ListenRandomPort(pMin, pMax)
|
|
if lis == nil {
|
|
log.Errorf(" %v ListenRandomPort err: %v", s.Target, err)
|
|
return
|
|
}
|
|
|
|
s.Serve = grpc.NewServer(
|
|
grpc.UnaryInterceptor(
|
|
func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
log.Errorf("server Panic: %v", r)
|
|
}
|
|
}()
|
|
resp, err = handler(ctx, req)
|
|
return
|
|
},
|
|
),
|
|
grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
|
|
MinTime: 20 * time.Second,
|
|
PermitWithoutStream: true,
|
|
}),
|
|
)
|
|
s.OnInit(s.Serve)
|
|
|
|
// 服务注册
|
|
if err = discover.RegisterGrpcServer(s.Target, s.SID, fmt.Sprintf("%v:%d", addr, port), s.EtcdTTL); err != nil {
|
|
log.Errorf("%v RegisterGrpcServer err: %v", s.Target, err)
|
|
return
|
|
}
|
|
if err = s.Serve.Serve(lis); err != nil {
|
|
log.Errorf(" %v Serve err: %v", s.Target, err)
|
|
return
|
|
}
|
|
log.Infof("%v server stop.", s.Target)
|
|
}()
|
|
}
|
|
|
|
func (s *ServiceBase) Close() {
|
|
if s.Serve != nil {
|
|
s.Serve.Stop()
|
|
s.wg.Wait()
|
|
}
|
|
}
|