Created
April 17, 2020 09:03
-
-
Save Merovius/63f67dd1a40f090e485c87bca55a4cb9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"net" | |
"google.golang.org/grpc" | |
"google.golang.org/grpc/examples/helloworld/helloworld" | |
) | |
func main() { | |
log.SetFlags(log.LstdFlags | log.Lshortfile) | |
ctx := context.Background() | |
MustListenAndServe("127.0.0.1:1234") | |
MustListenAndServe("127.0.0.2:1234") | |
MustListenAndServe("127.0.0.3:1234") | |
fmt.Println(MustConnectAndSayHello(ctx, "grpc-test.merovius.de:1234")) | |
fmt.Println(MustConnectAndSayHello(ctx, "dns:///grpc-test.merovius.de:1234")) | |
} | |
type greeter struct { | |
addr string | |
} | |
func MustListenAndServe(addr string) { | |
l, err := net.Listen("tcp", addr) | |
if err != nil { | |
log.Fatal(err) | |
} | |
srv := grpc.NewServer() | |
go func() { | |
log.Fatal(srv.Serve(l)) | |
}() | |
g := &greeter{addr} | |
helloworld.RegisterGreeterServer(srv, g) | |
} | |
func (g *greeter) SayHello(ctx context.Context, req *helloworld.HelloRequest) (*helloworld.HelloReply, error) { | |
return &helloworld.HelloReply{ | |
Message: g.addr, | |
}, nil | |
} | |
func MustConnectAndSayHello(ctx context.Context, target string) []string { | |
cc, err := grpc.DialContext(ctx, target, grpc.WithInsecure(), grpc.WithBalancerName("round_robin")) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer cc.Close() | |
hc := helloworld.NewGreeterClient(cc) | |
var out []string | |
for i := 0; i < 9; i++ { | |
rep, err := hc.SayHello(ctx, &helloworld.HelloRequest{}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
out = append(out, rep.Message) | |
} | |
return out | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment