git.colasdn.top/newrelic/go-agent@v3.26.0+incompatible/_integrations/nrmicro/example/pubsub/main.go (about) 1 // Copyright 2020 New Relic Corporation. All rights reserved. 2 // SPDX-License-Identifier: Apache-2.0 3 4 package main 5 6 import ( 7 "context" 8 "fmt" 9 "log" 10 "os" 11 "time" 12 13 "github.com/micro/go-micro" 14 newrelic "github.com/newrelic/go-agent" 15 "github.com/newrelic/go-agent/_integrations/nrmicro" 16 proto "github.com/newrelic/go-agent/_integrations/nrmicro/example/proto" 17 ) 18 19 func mustGetEnv(key string) string { 20 if val := os.Getenv(key); "" != val { 21 return val 22 } 23 panic(fmt.Sprintf("environment variable %s unset", key)) 24 } 25 26 func subEv(ctx context.Context, msg *proto.HelloRequest) error { 27 fmt.Println("Message received from", msg.GetName()) 28 return nil 29 } 30 31 func publish(s micro.Service, app newrelic.Application) { 32 c := s.Client() 33 34 for range time.NewTicker(time.Second).C { 35 txn := app.StartTransaction("publish", nil, nil) 36 msg := c.NewMessage("example.topic.pubsub", &proto.HelloRequest{Name: "Sally"}) 37 ctx := newrelic.NewContext(context.Background(), txn) 38 fmt.Println("Sending message") 39 if err := c.Publish(ctx, msg); nil != err { 40 log.Fatal(err) 41 } 42 txn.End() 43 } 44 } 45 46 func main() { 47 cfg := newrelic.NewConfig("Micro Pub/Sub", mustGetEnv("NEW_RELIC_LICENSE_KEY")) 48 cfg.Logger = newrelic.NewDebugLogger(os.Stdout) 49 app, err := newrelic.NewApplication(cfg) 50 if nil != err { 51 panic(err) 52 } 53 err = app.WaitForConnection(10 * time.Second) 54 if nil != err { 55 panic(err) 56 } 57 defer app.Shutdown(10 * time.Second) 58 59 s := micro.NewService( 60 micro.Name("go.micro.srv.pubsub"), 61 // Add the New Relic wrapper to the client which will create 62 // MessageProducerSegments for each Publish call. 63 micro.WrapClient(nrmicro.ClientWrapper()), 64 // Add the New Relic wrapper to the subscriber which will start a new 65 // transaction for each Subscriber invocation. 66 micro.WrapSubscriber(nrmicro.SubscriberWrapper(app)), 67 ) 68 s.Init() 69 70 go publish(s, app) 71 72 micro.RegisterSubscriber("example.topic.pubsub", s.Server(), subEv) 73 74 if err := s.Run(); err != nil { 75 log.Fatal(err) 76 } 77 }