3.1 IOC-golang 的接口注入
// +ioc:autowire=true// +ioc:autowire:type=singleton
type App struct { // 将实现注入至结构体指针 ServiceStruct *ServiceStruct `singleton:""` // 将实现注入至接口 ServiceImpl Service `singleton:"main.ServiceImpl1"`}
func GetServiceStructSingleton() (*ServiceStruct, error) {i, err := singleton.GetImpl("main.ServiceStruct", nil)if err != nil {return nil, err}impl := i.(*ServiceStruct)return impl, nil}
func GetServiceStructIOCInterfaceSingleton() (ServiceStructIOCInterface, error) { i, err := singleton.GetImplWithProxy("main.ServiceStruct", nil) if err != nil { return nil, err } impl := i.(ServiceStructIOCInterface) return impl, nil}
// +ioc:autowire=true// +ioc:autowire:type=singleton
type ServiceImpl struct {}
func (s *ServiceImpl) GetHelloString(name string) string { return fmt.Sprintf("This is ServiceImpl1, hello %s", name)}
type ServiceImplIOCInterface interface {GetHelloString(name string) string}
// +ioc:autowire=true// +ioc:autowire:type=singletontype App struct {// 注入 ServiceImpl 结构专属接口,无需在标签中指定结构IDServiceOwnInterface ServiceImplIOCInterface `singleton:""`}
3.2 代理的生成与注入
在前文提到生成的 zz.generated.ioc.go 代码中包含结构专属接口,同样,其中也包含结构代理的定义。还是以上文中提到的 ServiceImpl 结构为例,它生成的代理结构如下:
type serviceImpl1_ struct {GetHelloString_ func(name string) string}func (s *serviceImpl1_) GetHelloString(name string) string {return s.GetHelloString_(name)}
代理结构命名为小写字母开头的 $(结构名)_,其实现了“结构专属接口” 的全部方法,并将所有方法调用代理至 $(方法名)_ 的方法字段,该方法字段会被框架以反射的方式实现。
func init(){ normal.RegisterStructDescriptor(&autowire.StructDescriptor{ Factory: func() interface{} { return &serviceImpl1_{} // 注册代理结构 }, })}
4.1 方法、参数可观测
% iocli listgithub.com/alibaba/ioc-golang/extension/autowire/rpc/protocol/protocol_impl.IOCProtocol[]
github.com/ioc-golang/shopping-system/internal/auth.Authenticator[]
github.com/ioc-golang/shopping-system/pkg/service/festival/api.serviceIOCRPCClient[]
iocli watch github.com/ioc-golang/shopping-system/internal/auth.Authenticator Check
curl -i -X GET 'localhost:8080/festival/listCards?user_id=1&num=10'
% iocli watch github.com/ioc-golang/shopping-system/internal/auth.Authenticator Check========== On Call ==========github.com/ioc-golang/shopping-system/internal/auth.Authenticator.Check()Param 1: (int64) 1
========== On Response ==========github.com/ioc-golang/shopping-system/internal/auth.Authenticator.Check()Response 1: (bool) true
4.2 全链路追踪
参考链接:
[1]https://github.com/grpc-ecosystem/go-grpc-middleware
[2]https://github.com/alibaba/ioc-golang
[3]https://github.com/google/wire
[4]https://github.com/ioc-golang/shopping-system
开发者评测局第五期--Severless函数计算专场来啦
Beats耳机、机械键盘、千元天猫超市卡等你来拿,参与Severless评测抢“鲜”体验限量高级版产品。发布你的评测就有机会赢取大奖!
点击阅读原文查看详情。