// fetchToken 表示获取token 的动作,使用 tokensource 获取带时效时间的 token
perRPC:=oauth.TokenSource{TokenSource:oauth2.StaticTokenSource(fetchToken())}creds,err:=credentials.NewClientTLSFromFile(data.Path("x509/ca_cert.pem"),"x.test.example.com")iferr!=nil{log.Fatalf("failed to load credentials: %v",err)}opts:=[]grpc.DialOption{// In addition to the following grpc.DialOption, callers may also use
// the grpc.CallOption grpc.PerRPCCredentials with the RPC invocation
// itself.
// See: https://godoc.org/google.golang.org/grpc#PerRPCCredentials
grpc.WithPerRPCCredentials(perRPC),// oauth.TokenSource requires the configuration of transport
// credentials.
grpc.WithTransportCredentials(creds),}
// 流式的 验证
funcensureValidToken(ctxcontext.Context,reqany,info*grpc.UnaryServerInfo,handlergrpc.UnaryHandler)(any,error){md,ok:=metadata.FromIncomingContext(ctx)if!ok{returnnil,errMissingMetadata}// 下面这个是将客户端传的token 和服务器端的校验逻辑来比较
if!valid(md["authorization"]){returnnil,errInvalidToken}// Continue execution of handler after ensuring a valid token.
returnhandler(ctx,req)}cert,err:=tls.LoadX509KeyPair(data.Path("x509/server_cert.pem"),data.Path("x509/server_key.pem"))iferr!=nil{log.Fatalf("failed to load key pair: %s",err)}opts:=[]grpc.ServerOption{grpc.UnaryInterceptor(ensureValidToken),// Enable TLS for all incoming connections.
grpc.Creds(credentials.NewServerTLSFromCert(&cert)),}
varkacp=keepalive.ClientParameters{Time:10*time.Second,// send pings every 10 seconds if there is no activity
Timeout:time.Second,// wait 1 second for ping ack before considering the connection dead
PermitWithoutStream:true,// send pings even without active streams
}// 新建客户端时带上这个 grpc.DialOption
conn,err:=grpc.NewClient(*addr,grpc.WithTransportCredentials(insecure.NewCredentials()),grpc.WithKeepaliveParams(kacp))
负载平衡
默认的连接构建策略是 使用首个配置构建两件,如果需要使用负载平衡机制
1
2
3
4
5
6
// 使用轮转策略
roundrobinConn,err:=grpc.NewClient(fmt.Sprintf("%s:///%s",exampleScheme,exampleServiceName),grpc.WithDefaultServiceConfig(`{"loadBalancingConfig": [{"round_robin":{}}]}`),// This sets the initial balancing policy.
grpc.WithTransportCredentials(insecure.NewCredentials()),)