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

74 lines
1.8 KiB
Go

package svc
import (
"context"
"gitea.youtukeji.com.cn/youtu/youtu_grpc/app/auth_service/authservice"
"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"
"strings"
)
type ServiceContext struct {
Config config.Config
AuthServiceClient authservice.AuthService
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 = "/youtu/app/ecpm/config/"
func (svc *ServiceContext) initEtcd() {
svc.EcpmConfig = NewEcpmConfig()
//初始化etcd客户端
cli, err := clientv3.NewFromURL(viper.GetString(config.EtcdAddrKey))
if err != nil {
panic(err)
}
ch := make(chan config.WatchKV)
go config.EtcdGetOneAndWatch(context.Background(), cli, EcpmConfigWatchKey, ch)
for res := range ch {
svc.EcpmConfig.SetAllByJson(strings.TrimPrefix(res.Key, EcpmConfigWatchKey), res.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 = authservice.NewAuthService(zrpc.MustNewClient(clientConf))
}