
NewRelicでgRPC対応のGoエージェントが利用できるそうなので導入してみた
2021.06.11
この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
Announcing: Go agent adds support for gRPC! といういうのを見つけたので試してみました。
パッケージの詳細はnrgrpcを参考にしてください。
やってみる
GitHubにソースコード上げています
- init
 
go mod init newrelic-go-grpc
- get modules
 
go get -u \ google.golang.org/grpc \ google.golang.org/protobuf/proto \ github.com/golang/protobuf/proto \ github.com/grpc-ecosystem/go-grpc-middleware \ github.com/newrelic/go-agent \ github.com/newrelic/go-agent/_integrations/nrgrpc
- create protobuf
 
syntax = "proto3";
option go_package = "gen;gen";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
package helloworld;
// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}
// The response message containing the greetings
message HelloReply {
  string message = 1;
}
- generate interface
 
protoc \ --go_out=. --go_opt=paths=source_relative \ --go-grpc_out=. --go-grpc_opt=paths=source_relative \ proto/helloworld.proto
- coding
 
interceptorに追加するだけです
package main
import (
 "context"
 "log"
 "net"
 "os"
 pb "newrelic-go-grpc/proto"
 newrelic "github.com/newrelic/go-agent"
 "github.com/newrelic/go-agent/_integrations/nrgrpc"
 "google.golang.org/grpc"
)
const (
 port = ":50051"
)
type server struct {
 pb.UnimplementedGreeterServer
}
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
 return &pb.HelloReply{Message: "Hello World"}, nil
}
func main() {
 lis, err := net.Listen("tcp", port)
 if err != nil {
  log.Fatalf("failed to listen: %v", err)
 }
 cfg := newrelic.NewConfig("gRPC Server", os.Getenv("NEW_RELIC_LICENSE_KEY"))
 app, _ := newrelic.NewApplication(cfg)
 s := grpc.NewServer(
  grpc.UnaryInterceptor(
   nrgrpc.UnaryServerInterceptor(app),
  ),
 )
 pb.RegisterGreeterServer(s, &server{})
 if err := s.Serve(lis); err != nil {
  log.Fatalf("failed to serve: %v", err)
 }
}
- run server
 
NEW_RELIC_LICENSE_KEY=<your-license-key> go run server/main.go
- grpcurl
 
grpcurl \ -plaintext \ -import-path proto \ -proto helloworld.proto \ localhost:50051 helloworld.Greeter/SayHello
- check NewRelic dashboard
 
まとめ
今回は簡単に導入方法だけ解説しました。
次回はもっと細かい設定などを紹介できればと思います。
以上お疲れ様でした。









