| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"context" |
| 6 |
"fmt" |
| 7 |
"log" |
| 8 |
"net/http" |
| 9 |
"os" |
| 10 |
"strings" |
| 11 |
"time" |
| 12 |
|
| 13 |
"google.golang.org/grpc" |
| 14 |
|
| 15 |
"github.com/grpc-ecosystem/go-grpc-prometheus" |
| 16 |
pb "github.com/grpc-ecosystem/go-grpc-prometheus/examples/grpc-server-with-prometheus/protobuf" |
| 17 |
"github.com/prometheus/client_golang/prometheus" |
| 18 |
"github.com/prometheus/client_golang/prometheus/promhttp" |
| 19 |
) |
| 20 |
|
| 21 |
func main() { |
| 22 |
// Create a metrics registry. |
| 23 |
reg := prometheus.NewRegistry() |
| 24 |
// Create some standard client metrics. |
| 25 |
grpcMetrics := grpc_prometheus.NewClientMetrics() |
| 26 |
// Register client metrics to registry. |
| 27 |
reg.MustRegister(grpcMetrics) |
| 28 |
// Create a insecure gRPC channel to communicate with the server. |
| 29 |
conn, err := grpc.Dial( |
| 30 |
fmt.Sprintf("localhost:%v", 9093), |
| 31 |
grpc.WithUnaryInterceptor(grpcMetrics.UnaryClientInterceptor()), |
| 32 |
grpc.WithStreamInterceptor(grpcMetrics.StreamClientInterceptor()), |
| 33 |
grpc.WithInsecure(), |
| 34 |
) |
| 35 |
if err != nil { |
| 36 |
log.Fatal(err) |
| 37 |
} |
| 38 |
|
| 39 |
defer conn.Close() |
| 40 |
|
| 41 |
// Create a HTTP server for prometheus. |
| 42 |
httpServer := &http.Server{Handler: promhttp.HandlerFor(reg, promhttp.HandlerOpts{}), Addr: fmt.Sprintf("0.0.0.0:%d", 9094)} |
| 43 |
|
| 44 |
// Start your http server for prometheus. |
| 45 |
go func() { |
| 46 |
if err := httpServer.ListenAndServe(); err != nil { |
| 47 |
log.Fatal("Unable to start a http server.") |
| 48 |
} |
| 49 |
}() |
| 50 |
|
| 51 |
// Create a gRPC server client. |
| 52 |
client := pb.NewDemoServiceClient(conn) |
| 53 |
fmt.Println("Start to call the method called SayHello every 3 seconds") |
| 54 |
go func() { |
| 55 |
for { |
| 56 |
// Call “SayHello” method and wait for response from gRPC Server. |
| 57 |
_, err := client.SayHello(context.Background(), &pb.HelloRequest{Name: "Test"}) |
| 58 |
if err != nil { |
| 59 |
log.Printf("Calling the SayHello method unsuccessfully. ErrorInfo: %+v", err) |
| 60 |
log.Printf("You should to stop the process") |
| 61 |
return |
| 62 |
} |
| 63 |
time.Sleep(3 * time.Second) |
| 64 |
} |
| 65 |
}() |
| 66 |
scanner := bufio.NewScanner(os.Stdin) |
| 67 |
fmt.Println("You can press n or N to stop the process of client") |
| 68 |
for scanner.Scan() { |
| 69 |
if strings.ToLower(scanner.Text()) == "n" { |
| 70 |
os.Exit(0) |
| 71 |
} |
| 72 |
} |
| 73 |
} |