mirror of https://github.com/grpc/grpc-go.git
93 lines
2.4 KiB
Go
93 lines
2.4 KiB
Go
/*
|
|
*
|
|
* Copyright 2018 gRPC authors.
|
|
*
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*
|
|
*/
|
|
|
|
// Binary server demonstrates how to enable logging and Channelz for debugging
|
|
// gRPC services.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
rand "math/rand/v2"
|
|
"net"
|
|
"time"
|
|
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/channelz/service"
|
|
|
|
pb "google.golang.org/grpc/examples/helloworld/helloworld"
|
|
)
|
|
|
|
var (
|
|
ports = []string{":10001", ":10002", ":10003"}
|
|
)
|
|
|
|
// server is used to implement helloworld.GreeterServer.
|
|
type server struct {
|
|
pb.UnimplementedGreeterServer
|
|
}
|
|
|
|
// SayHello implements helloworld.GreeterServer
|
|
func (s *server) SayHello(_ context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
|
|
return &pb.HelloReply{Message: "Hello " + in.Name}, nil
|
|
}
|
|
|
|
// slow server is used to simulate a server that has a variable delay in its response.
|
|
type slowServer struct {
|
|
pb.UnimplementedGreeterServer
|
|
}
|
|
|
|
// SayHello implements helloworld.GreeterServer
|
|
func (s *slowServer) SayHello(_ context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
|
|
// Delay 100ms ~ 200ms before replying
|
|
time.Sleep(time.Duration(100+rand.IntN(100)) * time.Millisecond)
|
|
return &pb.HelloReply{Message: "Hello " + in.Name}, nil
|
|
}
|
|
|
|
func main() {
|
|
/***** Set up the server serving channelz service. *****/
|
|
lis, err := net.Listen("tcp", ":50052")
|
|
if err != nil {
|
|
log.Fatalf("failed to listen: %v", err)
|
|
}
|
|
defer lis.Close()
|
|
s := grpc.NewServer()
|
|
service.RegisterChannelzServiceToServer(s)
|
|
go s.Serve(lis)
|
|
defer s.Stop()
|
|
|
|
/***** Start three GreeterServers(with one of them to be the slowServer). *****/
|
|
for i := 0; i < 3; i++ {
|
|
lis, err := net.Listen("tcp", ports[i])
|
|
if err != nil {
|
|
log.Fatalf("failed to listen: %v", err)
|
|
}
|
|
defer lis.Close()
|
|
s := grpc.NewServer()
|
|
if i == 2 {
|
|
pb.RegisterGreeterServer(s, &slowServer{})
|
|
} else {
|
|
pb.RegisterGreeterServer(s, &server{})
|
|
}
|
|
go s.Serve(lis)
|
|
}
|
|
|
|
/***** Wait for user exiting the program *****/
|
|
select {}
|
|
}
|