在go语言中将jaeger集成到grpc服务中的流程步骤
本文对Grpc不做介绍了,如果您不了解Grpc,需要先了解Grpc,先获取Jaeger-grpc的代码:
github.com/iceymoss/Learning-notes
jaeger_test中
Server示例:
package main
import (
"context"
"fmt"
"log"
"net"
"StudyGin/jaeger_test/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
type HelloSerivce struct{}
func (h *HelloSerivce) SayHello(c context.Context, req *proto.HelloRequest) (*proto.HelloReply, error) {
//接收context中的内容
md, ok := metadata.FromIncomingContext(c)
if !ok {
fmt.Println("get metadata err", ok)
}
for key, value := range md {
fmt.Printf("%v: %v\n", key, value)
}
return &proto.HelloReply{
Id: "123456789",
Request: req,
}, nil
}
func (h *HelloSerivce) Ping(context.Context, *proto.IsEmpty) (*proto.Pong, error) {
return nil, nil
}
func main() {
//实例化server
lit, err := net.Listen("tcp", ":50051")
if err != nil {
log.Panicln("监听失败", err)
}
//注册处理逻辑
//NewServer创建一个未注册服务且尚未开始接受请求的 gRPC 服务器。
s := grpc.NewServer()
proto.RegisterGreeterServer(s, &HelloSerivce{})
log.Println(s.Serve(lit))
}
Client示例:
package main
import (
"context"
"fmt"
"log"
"time"
"StudyGin/jaeger_test/otgrpc"
"StudyGin/jaeger_test/proto"
"github.com/opentracing/opentracing-go"
"github.com/uber/jaeger-client-go"
jaegercfg "github.com/uber/jaeger-client-go/config"
"google.golang.org/grpc"
timepb "google.golang.org/protobuf/types/known/timestamppb"
)
func main() {
//日志追踪初始化配置
cfg := jaegercfg.Configuration{
Sampler: &jaegercfg.SamplerConfig{
Type: jaeger.SamplerTypeConst,
Param: 1,
},
Reporter: &jaegercfg.ReporterConfig{
LogSpans: true,
LocalAgentHostPort: "127.0.0.1:6831",
},
ServiceName: "mxshop",
}
//初始化跟踪连
Tracer, Closer, err := cfg.NewTracer(jaegercfg.Logger(jaeger.StdLogger))
if err != nil {
panic(err)
}
//将tracer设置为全局
opentracing.SetGlobalTracer(Tracer)
defer Closer.Close()
clientConn, err := grpc.Dial("localhost:50051", grpc.WithInsecure(), grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(opentracing.GlobalTracer())))
if err != nil {
log.Panicln("连接失败", err)
}
defer clientConn.Close()
client := proto.NewGreeterClient(clientConn)
res, err := client.SayHello(context.Background(), &proto.HelloRequest{
Name: "kuangyang",
Url: "learinku.com",
Gender: proto.Gender_MALE,
M: map[string]string{
"来自": "无锡",
"现居": "无锡",
},
AddTime: timepb.New(time.Now()),
})
if err != nil {
panic(err)
}
//pong, err := client.Ping(context.Background(), &proto.IsEmpty{})
//if err != nil {
// panic(err)
//}
fmt.Printf("返回结果: %v", res)
}
这样我们可以到jaeger的ui界面查看本次调用的链路数据,
这里就不截图了,感兴趣的可以自行测试
相关文章