-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
100 lines (91 loc) · 2.47 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package di
import (
"context"
"errors"
"fmt"
"github.com/JerryZhou343/leaf-go/api/rpc"
"github.com/JerryZhou343/leaf-go/infra/conf"
"github.com/bilibili/kratos/pkg/conf/env"
"github.com/bilibili/kratos/pkg/log"
"github.com/bilibili/kratos/pkg/naming"
"github.com/bilibili/kratos/pkg/naming/discovery"
"github.com/bilibili/kratos/pkg/naming/etcd"
"github.com/bilibili/kratos/pkg/net/ip"
"github.com/bilibili/kratos/pkg/net/rpc/warden"
"go.etcd.io/etcd/clientv3"
"os"
"strings"
"time"
)
var (
nsEtcd *etcd.EtcdBuilder
nsDiscovery *discovery.Discovery
)
type App struct {
svcHandler *rpc.Handler
grpc *warden.Server
config *conf.Config
ds *etcd.EtcdBuilder
}
func NewApp(svcHandler *rpc.Handler, g *warden.Server, config *conf.Config) (app *App, closeFunc func(), err error) {
var (
unregister context.CancelFunc
internalIP string
)
app = &App{
svcHandler: svcHandler,
grpc: g,
config: config,
}
//服务注册
hostName, _ := os.Hostname()
internalIP = ip.InternalIP()
addrInfo := strings.Split(config.Grpc.Addr, ":")
if len(addrInfo) != 2 {
err = errors.New("server addr config error :" + config.Grpc.Addr)
return
}
addrs := []string{fmt.Sprintf("%s:%s", internalIP, addrInfo[1])}
ins := &naming.Instance{
Region: env.Region,
Zone: env.Zone,
Env: env.DeployEnv,
AppID: env.AppID,
Hostname: hostName,
Addrs: addrs,
Version: "",
LastTs: 0,
Metadata: nil,
Status: 0,
}
unregister, err = app.registerDiscovery(ins)
//unregister, err = app.registerEtcd(ins)
closeFunc = func() {
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
if err := g.Shutdown(ctx); err != nil {
log.Error("grpcSrv.Shutdown error(%v)", err)
}
cancel()
unregister()
}
return
}
func (a *App) registerDiscovery(ins *naming.Instance) (unregister context.CancelFunc, err error) {
nsDiscovery = discovery.New(nil)
unregister, err = nsDiscovery.Register(context.Background(), ins)
return
}
func (a *App) registerEtcd(ins *naming.Instance) (unregister context.CancelFunc, err error) {
nodes := strings.Split(env.DiscoveryNodes, ",")
cfg := &clientv3.Config{
Endpoints: nodes,
AutoSyncInterval: time.Second,
DialTimeout: 5 * time.Second,
DialKeepAliveTime: time.Second,
DialKeepAliveTimeout: 6 * time.Second,
Context: context.Background(),
}
nsEtcd, err = etcd.New(cfg)
unregister, err = nsEtcd.Register(context.Background(), ins)
return
}