youtu_grpc/app/ecpm_service/internal/svc/service_context.go

74 lines
1.8 KiB
Go
Raw Normal View History

2025-02-05 18:45:49 +08:00
package svc
2025-02-07 15:17:01 +08:00
import (
"context"
2025-02-14 17:46:27 +08:00
"gitea.youtukeji.com.cn/youtu/youtu_grpc/app/auth_service/authservice"
"gitea.youtukeji.com.cn/youtu/youtu_grpc/pkg/config"
"github.com/spf13/viper"
2025-02-07 15:17:01 +08:00
"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"
2025-02-24 17:27:51 +08:00
"strings"
2025-02-07 15:17:01 +08:00
)
2025-02-05 18:45:49 +08:00
type ServiceContext struct {
2025-02-07 15:17:01 +08:00
Config config.Config
2025-02-14 17:46:27 +08:00
AuthServiceClient authservice.AuthService
2025-02-07 15:17:01 +08:00
etcdCli *clientv3.Client
EcpmConfig *EcpmConfigCli
2025-02-05 18:45:49 +08:00
}
func NewServiceContext(c config.Config) *ServiceContext {
2025-02-07 15:17:01 +08:00
svc := &ServiceContext{
2025-02-05 18:45:49 +08:00
Config: c,
}
2025-02-07 15:17:01 +08:00
//初始化etcd客户端
svc.initEtcd()
//初始化auth_service客户端
svc.initAuthServiceClient()
return svc
}
2025-02-24 17:27:51 +08:00
const EcpmConfigWatchKey = "/youtu/app/ecpm/config/"
2025-02-07 15:17:01 +08:00
func (svc *ServiceContext) initEtcd() {
2025-02-12 18:37:51 +08:00
svc.EcpmConfig = NewEcpmConfig()
2025-02-07 15:17:01 +08:00
//初始化etcd客户端
cli, err := clientv3.NewFromURL(viper.GetString(config.EtcdAddrKey))
2025-02-07 15:17:01 +08:00
if err != nil {
panic(err)
}
2025-02-24 17:27:51 +08:00
ch := make(chan config.WatchKV)
go config.EtcdGetOneAndWatch(context.Background(), cli, EcpmConfigWatchKey, ch)
2025-02-07 15:17:01 +08:00
2025-02-24 17:27:51 +08:00
for res := range ch {
svc.EcpmConfig.SetAllByJson(strings.TrimPrefix(res.Key, EcpmConfigWatchKey), res.Value)
2025-02-07 15:17:01 +08:00
}
svc.etcdCli = cli
}
// initAuthServiceClient inits the AuthServiceClient.
func (svc *ServiceContext) initAuthServiceClient() {
clientConf := zrpc.RpcClientConf{}
err := conf.FillDefault(&clientConf) // 填充默认值,比如 trace 透传等,参考服务配置说明
if err != nil {
panic(err)
}
2025-02-14 17:30:53 +08:00
clientConf.Token = "auth_service.rpc.key"
clientConf.App = "auth_service.rpc"
2025-02-07 15:17:01 +08:00
clientConf.Etcd = discov.EtcdConf{ // 通过 etcd 服务发现
Hosts: []string{viper.GetString(config.EtcdAddrKey)},
2025-02-14 17:30:53 +08:00
Key: "auth_service.rpc",
2025-02-07 15:17:01 +08:00
}
2025-02-14 17:46:27 +08:00
svc.AuthServiceClient = authservice.NewAuthService(zrpc.MustNewClient(clientConf))
2025-02-05 18:45:49 +08:00
}