github.com/Go-To-Byte/DouSheng/user_center@v0.0.0-20230524130918-ad531c1a3f6a/client/rpc/client.go (about) 1 // @Author: Ciusyan 2023/2/8 2 package rpc 3 4 import ( 5 "github.com/infraboard/mcube/logger" 6 "github.com/infraboard/mcube/logger/zap" 7 "os" 8 9 "github.com/Go-To-Byte/DouSheng/dou_kit/client" 10 "github.com/Go-To-Byte/DouSheng/dou_kit/conf" 11 "github.com/Go-To-Byte/DouSheng/dou_kit/exception" 12 13 "github.com/Go-To-Byte/DouSheng/user_center/apps/user" 14 ) 15 16 // 用户中心 rpc 服务的 SDK 17 18 const ( 19 discoverName = "user_center" 20 ) 21 22 type UserCenterClient struct { 23 userService user.ServiceClient 24 25 l logger.Logger 26 } 27 28 // NewUserCenterClientFromCfg 从配置文件读取注册中心配置 29 func NewUserCenterClientFromCfg() (*UserCenterClient, error) { 30 // 注册中心配置 [从配置文件中读取] 31 cfg := conf.C().Consul.Discovers[discoverName] 32 33 // 根据注册中心的配置,获取用户中心的客户端 34 clientSet, err := client.NewClientSet(cfg) 35 36 if err != nil { 37 return nil, 38 exception.WithStatusMsgf("获取服务[%s]失败:%s", cfg.DiscoverName, err.Error()) 39 } 40 return newDefault(clientSet), nil 41 } 42 43 // NewUserCenterClientFromEnv 从环境变量读取注册中心配置 44 func NewUserCenterClientFromEnv() (*UserCenterClient, error) { 45 // 注册中心配置 [从环境变量文件中读取] 46 47 cfg := conf.NewDefaultDiscover() 48 cfg.SetAddr(os.Getenv("CONSUL_ADDR")) 49 cfg.SetDiscoverName(os.Getenv("CONSUL_DISCOVER_NAME")) 50 51 // 去发现 user_center 服务 52 // 根据注册中心的配置,获取用户中心的客户端 53 clientSet, err := client.NewClientSet(cfg) 54 55 if err != nil { 56 return nil, 57 exception.WithStatusMsgf("获取服务[%s]失败:%s", cfg.DiscoverName, err.Error()) 58 } 59 return newDefault(clientSet), nil 60 } 61 62 func newDefault(clientSet *client.ClientSet) *UserCenterClient { 63 conn := clientSet.Conn() 64 return &UserCenterClient{ 65 l: zap.L().Named("USER_CENTER_RPC"), 66 67 // User 服务 68 userService: user.NewServiceClient(conn), 69 } 70 } 71 72 func (c *UserCenterClient) UserService() user.ServiceClient { 73 if c.userService == nil { 74 c.l.Errorf("获取用户中心[Token Client]失败") 75 return nil 76 } 77 return c.userService 78 }