grpc 集成 opentelemetry

服务端代码:

package main

import (
   "context"
   "flag"
   "fmt"
   "go.opentelemetry.io/otel"
   "go.opentelemetry.io/otel/attribute"
   "go.opentelemetry.io/otel/exporters/jaeger"
   "go.opentelemetry.io/otel/propagation"
   "go.opentelemetry.io/otel/sdk/resource"
   "go.opentelemetry.io/otel/sdk/trace"
   "google.golang.org/grpc/codes"
   "google.golang.org/grpc/status"
   "log"
   "net"

   pb "GoStart/error/rpc"
   "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
   "google.golang.org/grpc"

   semconv "go.opentelemetry.io/otel/semconv/v1.12.0"
)

const (
   traceName = "mxshop-otel"
)

var tp *trace.TracerProvider

func tracerProvider() error {
   url := "http://127.0.0.1:14268/api/traces"
   jexp, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(url)))
   if err != nil {
      panic(err)
   }

   tp = trace.NewTracerProvider(
      trace.WithBatcher(jexp),
      trace.WithResource(
         resource.NewWithAttributes(
            semconv.SchemaURL,
            semconv.ServiceNameKey.String("mxshop-user"),
            attribute.String("environment", "dev"),
            attribute.Int("ID", 1),
         ),
      ),
   )
   otel.SetTracerProvider(tp)
   otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
   return nil
}

var (
   port = flag.Int("port", 50052, "The server port")
)

// server is used to implement helloworld.GreeterServer.
type server struct {
   pb.UnimplementedGreeterServer
}

// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
   log.Printf("Received: %v", in.GetName())
   return nil, status.Error(codes.NotFound, "user not found")
   //return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
}

func main() {
   _ = tracerProvider()
   flag.Parse()
   lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
   if err != nil {
      log.Fatalf("failed to listen: %v", err)
   }
    //添加拦截器(grpc集成OpenTelemetry主要是调用(otelgrpc.UnaryServerInterceptor()) 
   s := grpc.NewServer(grpc.UnaryInterceptor(otelgrpc.UnaryServerInterceptor()))
   pb.RegisterGreeterServer(s, &server{})
   log.Printf("server listening at %v", lis.Addr())
   if err := s.Serve(lis); err != nil {
      log.Fatalf("failed to serve: %v", err)
   }
}

客户端代码:

package main

import (
   "context"
   "flag"
   "fmt"
   "go.opentelemetry.io/otel"
   "go.opentelemetry.io/otel/attribute"
   "go.opentelemetry.io/otel/exporters/jaeger"
   "go.opentelemetry.io/otel/propagation"
   "go.opentelemetry.io/otel/sdk/resource"
   "go.opentelemetry.io/otel/sdk/trace"
   "log"
   "time"

   pb "GoStart/error/rpc"
   "google.golang.org/grpc"
   "google.golang.org/grpc/credentials/insecure"
   "google.golang.org/grpc/status"

   "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
   semconv "go.opentelemetry.io/otel/semconv/v1.12.0"
)

const (
   traceName = "mxshop-otel"
)

var tp *trace.TracerProvider

func tracerProvider() error {
   url := "http://127.0.0.1:14268/api/traces"
   jexp, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(url)))
   if err != nil {
      panic(err)
   }

   tp = trace.NewTracerProvider(
      trace.WithBatcher(jexp),
      trace.WithResource(
         resource.NewWithAttributes(
            semconv.SchemaURL,
            semconv.ServiceNameKey.String("mxshop-user"),
            attribute.String("environment", "dev"),
            attribute.Int("ID", 1),
         ),
      ),
   )
   otel.SetTracerProvider(tp)
   otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
   return nil
}

const (
   defaultName = "world"
)

var (
   addr = flag.String("addr", "localhost:50052", "the address to connect to")
   name = flag.String("name", defaultName, "Name to greet")
)

func main() {
   _ = tracerProvider()

   flag.Parse()
   // Set up a connection to the server.
   conn, err := grpc.Dial(*addr,
      grpc.WithTransportCredentials(insecure.NewCredentials()),
       //添加拦截器(grpc集成OpenTelemetry主要是调用(otelgrpc.UnaryClientInterceptor())                    
      grpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor()),
   )
   if err != nil {
      log.Fatalf("did not connect: %v", err)
   }
   defer conn.Close()
   c := pb.NewGreeterClient(conn)

   // Contact the server and print out its response.
   ctx, cancel := context.WithTimeout(context.Background(), time.Second)
   defer cancel()
   r, err := c.SayHello(ctx, &pb.HelloRequest{Name: *name})
   if err != nil {
      s, ok := status.FromError(err)
      if !ok {
         log.Fatalf("err is not standard grpc error: %v", err)
      }
      fmt.Println(s.Code())
   }
   log.Printf("Greeting: %s", r.GetMessage())
}

你可能感兴趣的:(GO开发工程师系列,golang)