youtu_grpc/app/ecpm_service/internal/svc/service_context.go
2025-02-14 17:31:28 +08:00

88 lines
2.0 KiB
Go

package svc
import (
"context"
"gitea.youtukeji.com.cn/youtu/youtu_grpc/app/auth_service/auth"
"gitea.youtukeji.com.cn/youtu/youtu_grpc/pkg/config"
"github.com/spf13/viper"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/discov"
"github.com/zeromicro/go-zero/zrpc"
clientv3 "go.etcd.io/etcd/client/v3"
)
type ServiceContext struct {
Config config.Config
AuthServiceClient auth.AuthServiceClient
etcdCli *clientv3.Client
EcpmConfig *EcpmConfigCli
}
func NewServiceContext(c config.Config) *ServiceContext {
svc := &ServiceContext{
Config: c,
}
//初始化etcd客户端
svc.initEtcd()
//初始化auth_service客户端
svc.initAuthServiceClient()
return svc
}
const EcpmConfigWatchKey = "ecpm_config"
func (svc *ServiceContext) initEtcd() {
svc.EcpmConfig = NewEcpmConfig()
//初始化etcd客户端
cli, err := clientv3.NewFromURL(viper.GetString(config.EtcdAddrKey))
if err != nil {
panic(err)
}
//获取ecpm配置
res, err := cli.Get(context.Background(), EcpmConfigWatchKey)
if err != nil {
panic(err)
}
//设置ecpm配置
for _, kv := range res.Kvs {
svc.EcpmConfig.SetAllByJson(kv.Value)
}
//监听etcd
go func() {
ch := cli.Watch(context.Background(), EcpmConfigWatchKey)
//从通道中尝试取值(监视的信息)
for res := range ch {
for _, evt := range res.Events {
svc.EcpmConfig.SetAllByJson(evt.Kv.Value)
}
}
}()
svc.etcdCli = cli
}
// initAuthServiceClient inits the AuthServiceClient.
func (svc *ServiceContext) initAuthServiceClient() {
clientConf := zrpc.RpcClientConf{}
err := conf.FillDefault(&clientConf) // 填充默认值,比如 trace 透传等,参考服务配置说明
if err != nil {
panic(err)
}
clientConf.Token = "auth_service.rpc.key"
clientConf.App = "auth_service.rpc"
clientConf.Etcd = discov.EtcdConf{ // 通过 etcd 服务发现
Hosts: []string{viper.GetString(config.EtcdAddrKey)},
Key: "auth_service.rpc",
}
svc.AuthServiceClient = auth.NewAuthServiceClient(zrpc.MustNewClient(clientConf).Conn())
}