当前位置: 首页>>代码示例>>Golang>>正文


Golang grpc.Dial函数代码示例

本文整理汇总了Golang中google/golang.org/grpc.Dial函数的典型用法代码示例。如果您正苦于以下问题:Golang Dial函数的具体用法?Golang Dial怎么用?Golang Dial使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Dial函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestCredentialsMisuse

func TestCredentialsMisuse(t *testing.T) {
	creds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", "x.test.youtube.com")
	if err != nil {
		t.Fatalf("Failed to create credentials %v", err)
	}
	// Two conflicting credential configurations
	if _, err := grpc.Dial("Non-Existent.Server:80", grpc.WithTransportCredentials(creds), grpc.WithTimeout(time.Millisecond), grpc.WithBlock(), grpc.WithInsecure()); err != grpc.ErrCredentialsMisuse {
		t.Fatalf("grpc.Dial(_, _) = _, %v, want _, %v", err, grpc.ErrCredentialsMisuse)
	}
	// security info on insecure connection
	if _, err := grpc.Dial("Non-Existent.Server:80", grpc.WithPerRPCCredentials(creds), grpc.WithTimeout(time.Millisecond), grpc.WithBlock(), grpc.WithInsecure()); err != grpc.ErrCredentialsMisuse {
		t.Fatalf("grpc.Dial(_, _) = _, %v, want _, %v", err, grpc.ErrCredentialsMisuse)
	}
}
开发者ID:johnmccawley,项目名称:origin,代码行数:14,代码来源:end2end_test.go

示例2: setUp

func setUp(hs *health.HealthServer, maxStream uint32, ua string, e env) (s *grpc.Server, cc *grpc.ClientConn) {
	sopts := []grpc.ServerOption{grpc.MaxConcurrentStreams(maxStream)}
	la := ":0"
	switch e.network {
	case "unix":
		la = "/tmp/testsock" + fmt.Sprintf("%d", time.Now())
		syscall.Unlink(la)
	}
	lis, err := net.Listen(e.network, la)
	if err != nil {
		grpclog.Fatalf("Failed to listen: %v", err)
	}
	if e.security == "tls" {
		creds, err := credentials.NewServerTLSFromFile(tlsDir+"server1.pem", tlsDir+"server1.key")
		if err != nil {
			grpclog.Fatalf("Failed to generate credentials %v", err)
		}
		sopts = append(sopts, grpc.Creds(creds))
	}
	s = grpc.NewServer(sopts...)
	if hs != nil {
		healthpb.RegisterHealthCheckServer(s, hs)
	}
	testpb.RegisterTestServiceServer(s, &testServer{})
	go s.Serve(lis)
	addr := la
	switch e.network {
	case "unix":
	default:
		_, port, err := net.SplitHostPort(lis.Addr().String())
		if err != nil {
			grpclog.Fatalf("Failed to parse listener address: %v", err)
		}
		addr = "localhost:" + port
	}
	if e.security == "tls" {
		creds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", "x.test.youtube.com")
		if err != nil {
			grpclog.Fatalf("Failed to create credentials %v", err)
		}
		cc, err = grpc.Dial(addr, grpc.WithTransportCredentials(creds), grpc.WithDialer(e.dialer), grpc.WithUserAgent(ua))
	} else {
		cc, err = grpc.Dial(addr, grpc.WithDialer(e.dialer), grpc.WithUserAgent(ua))
	}
	if err != nil {
		grpclog.Fatalf("Dial(%q) = %v", addr, err)
	}
	return
}
开发者ID:ELMERzark,项目名称:grpc-go,代码行数:49,代码来源:end2end_test.go

示例3: newEventsClientConnectionWithAddress

//newEventsClientConnectionWithAddress Returns a new grpc.ClientConn to the configured local PEER.
func newEventsClientConnectionWithAddress(peerAddress string) (*grpc.ClientConn, error) {
	var opts []grpc.DialOption
	if peer.TLSEnabled() {
		var sn string
		if viper.GetString("peer.tls.serverhostoverride") != "" {
			sn = viper.GetString("peer.tls.serverhostoverride")
		}
		var creds credentials.TransportAuthenticator
		if viper.GetString("peer.tls.cert.file") != "" {
			var err error
			creds, err = credentials.NewClientTLSFromFile(viper.GetString("peer.tls.cert.file"), sn)
			if err != nil {
				grpclog.Fatalf("Failed to create TLS credentials %v", err)
			}
		} else {
			creds = credentials.NewClientTLSFromCert(nil, sn)
		}
		opts = append(opts, grpc.WithTransportCredentials(creds))
	}
	opts = append(opts, grpc.WithTimeout(defaultTimeout))
	opts = append(opts, grpc.WithBlock())
	opts = append(opts, grpc.WithInsecure())

	return grpc.Dial(peerAddress, opts...)
}
开发者ID:magooster,项目名称:obc-peer,代码行数:26,代码来源:consumer.go

示例4: deleteRangeCommandFunc

// deleteRangeCommandFunc executes the "delegeRange" command.
func deleteRangeCommandFunc(c *cli.Context) {
	if len(c.Args()) == 0 {
		panic("bad arg")
	}

	var rangeEnd []byte
	key := []byte(c.Args()[0])
	if len(c.Args()) > 1 {
		rangeEnd = []byte(c.Args()[1])
	}
	conn, err := grpc.Dial("127.0.0.1:12379")
	if err != nil {
		panic(err)
	}
	etcd := pb.NewEtcdClient(conn)
	req := &pb.DeleteRangeRequest{Key: key, RangeEnd: rangeEnd}

	etcd.DeleteRange(context.Background(), req)

	if rangeEnd != nil {
		fmt.Printf("range [%s, %s) is deleted\n", string(key), string(rangeEnd))
	} else {
		fmt.Printf("key %s is deleted\n", string(key))
	}
}
开发者ID:Celluliodio,项目名称:flannel,代码行数:26,代码来源:delete_range_command.go

示例5: main

func main() {
	flag.Parse()
	args := flag.Args()
	var values []int32
	for _, arg := range args[1:] {
		value, _ := strconv.Atoi(arg)
		values = append(values, int32(value))
	}
	arg, _ := strconv.Atoi(args[0])
	testType := TestType(arg)

	// Accumulate gRPC options
	var opts []grpc.DialOption

	// Connect via insecure
	opts = append(opts, grpc.WithInsecure())

	// Dial the server
	conn, err := grpc.Dial("127.0.0.1:1234", opts...)
	if err != nil {
		log.Fatalln("fail to dial:", err)
	}
	defer conn.Close()

	// Get a client using the connection
	client := NewBetterTestClient(conn)
	resp, err := client.Add(context.Background(), &BetterNumericRequest{Type: testType, Values: values})
	if err != nil {
		log.Fatalln("failed server call:", err)
	}
	log.Println("resp:", resp)
}
开发者ID:vaskoz,项目名称:grpc-intro,代码行数:32,代码来源:client_better.go

示例6: newSession

func newSession(ctx context.Context, agent *Agent, delay time.Duration, sessionID string, description *api.NodeDescription) *session {
	s := &session{
		agent:         agent,
		sessionID:     sessionID,
		errs:          make(chan error, 1),
		messages:      make(chan *api.SessionMessage),
		assignments:   make(chan *api.AssignmentsMessage),
		subscriptions: make(chan *api.SubscriptionMessage),
		registered:    make(chan struct{}),
		closed:        make(chan struct{}),
	}

	// TODO(stevvooe): Need to move connection management up a level or create
	// independent connection for log broker client.

	peer, err := agent.config.Managers.Select()
	if err != nil {
		s.errs <- err
		return s
	}
	cc, err := grpc.Dial(peer.Addr,
		grpc.WithTransportCredentials(agent.config.Credentials),
		grpc.WithTimeout(dispatcherRPCTimeout),
	)
	if err != nil {
		s.errs <- err
		return s
	}
	s.addr = peer.Addr
	s.conn = cc

	go s.run(ctx, delay, description)
	return s
}
开发者ID:harche,项目名称:docker,代码行数:34,代码来源:session.go

示例7: DialTablet

// DialTablet creates and initializes gRPCQueryClient.
func DialTablet(ctx context.Context, endPoint *pbt.EndPoint, keyspace, shard string, timeout time.Duration) (tabletconn.TabletConn, error) {
	// create the RPC client
	addr := netutil.JoinHostPort(endPoint.Host, endPoint.PortMap["grpc"])
	cc, err := grpc.Dial(addr, grpc.WithBlock(), grpc.WithTimeout(timeout))
	if err != nil {
		return nil, err
	}
	c := pbs.NewQueryClient(cc)

	result := &gRPCQueryClient{
		endPoint: endPoint,
		cc:       cc,
		c:        c,
	}
	if keyspace != "" || shard != "" {
		gsir, err := c.GetSessionId(ctx, &pb.GetSessionIdRequest{
			Keyspace: keyspace,
			Shard:    shard,
		})
		if err != nil {
			cc.Close()
			return nil, err
		}
		if gsir.Error != nil {
			cc.Close()
			return nil, tabletErrorFromRPCError(gsir.Error)
		}
		result.sessionID = gsir.SessionId
	}

	return result, nil
}
开发者ID:afrolovskiy,项目名称:vitess,代码行数:33,代码来源:conn.go

示例8: main

func main() {
	config := config.Load()

	var chainID string
	var serverAddr string
	var windowSize uint64

	flag.StringVar(&serverAddr, "server", fmt.Sprintf("%s:%d", config.General.ListenAddress, config.General.ListenPort), "The RPC server to connect to.")
	flag.StringVar(&chainID, "chainID", provisional.TestChainID, "The chain ID to deliver from.")
	flag.Uint64Var(&windowSize, "windowSize", 10, "The window size for the deliver.")
	flag.Parse()

	conn, err := grpc.Dial(serverAddr, grpc.WithInsecure())
	if err != nil {
		fmt.Println("Error connecting:", err)
		return
	}
	client, err := ab.NewAtomicBroadcastClient(conn).Deliver(context.TODO())
	if err != nil {
		fmt.Println("Error connecting:", err)
		return
	}

	s := newDeliverClient(client, chainID, windowSize)
	s.seekOldest()
	s.readUntilClose()

}
开发者ID:hyperledger,项目名称:fabric,代码行数:28,代码来源:client.go

示例9: clientSetUp

func clientSetUp(t *testing.T, addr string, cg grpc.CompressorGenerator, dg grpc.DecompressorGenerator, ua string, e env) (cc *grpc.ClientConn) {
	var derr error
	if e.security == "tls" {
		creds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", "x.test.youtube.com")
		if err != nil {
			t.Fatalf("Failed to create credentials %v", err)
		}
		cc, derr = grpc.Dial(addr, grpc.WithTransportCredentials(creds), grpc.WithDialer(e.dialer), grpc.WithUserAgent(ua), grpc.WithCompressor(cg), grpc.WithDecompressor(dg))
	} else {
		cc, derr = grpc.Dial(addr, grpc.WithDialer(e.dialer), grpc.WithInsecure(), grpc.WithUserAgent(ua), grpc.WithCompressor(cg), grpc.WithDecompressor(dg))
	}
	if derr != nil {
		t.Fatalf("Dial(%q) = %v", addr, derr)
	}
	return
}
开发者ID:slafgod000,项目名称:grpc-go,代码行数:16,代码来源:end2end_test.go

示例10: DialGRPC

// DialGRPC returns a GRPC connection for use communicating with a Google cloud
// service, configured with the given ClientOptions.
func DialGRPC(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) {
	var o internal.DialSettings
	for _, opt := range opts {
		opt.Apply(&o)
	}
	if o.HTTPClient != nil {
		return nil, errors.New("unsupported HTTP client specified")
	}
	if o.GRPCConn != nil {
		return o.GRPCConn, nil
	}
	if o.TokenSource == nil {
		var err error
		o.TokenSource, err = google.DefaultTokenSource(ctx, o.Scopes...)
		if err != nil {
			return nil, fmt.Errorf("google.DefaultTokenSource: %v", err)
		}
	}
	grpcOpts := []grpc.DialOption{
		grpc.WithPerRPCCredentials(oauth.TokenSource{o.TokenSource}),
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
	}
	if appengineDialerHook != nil {
		// Use the Socket API on App Engine.
		grpcOpts = append(grpcOpts, appengineDialerHook(ctx))
	}
	grpcOpts = append(grpcOpts, o.GRPCDialOpts...)
	if o.UserAgent != "" {
		grpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent))
	}
	return grpc.Dial(o.Endpoint, grpcOpts...)
}
开发者ID:Ropes,项目名称:pubbing,代码行数:34,代码来源:dial.go

示例11: ExampleNewWriter

func ExampleNewWriter(serverPort int, resourceName string) {
	ctx := context.Background()
	conn, err := grpc.Dial(fmt.Sprintf("localhost:%d", serverPort), grpc.WithInsecure())
	if err != nil {
		log.Printf("grpc.Dial: %v", err)
		return
	}
	client := NewClient(conn)

	w, err := client.NewWriter(ctx, resourceName)
	if err != nil {
		log.Printf("NewWriter: %v", err)
		return
	}
	defer func() {
		err := w.Close()
		if err != nil {
			log.Printf("Close: %v", err)
		}
	}()

	buf := []byte("hello world")
	n, err := w.Write(buf)
	if err != nil {
		log.Printf("Write: %v", err)
	}
	log.Printf("Wrote %d bytes", n)
}
开发者ID:trythings,项目名称:trythings,代码行数:28,代码来源:examples_test.go

示例12: getVersionAPIClient

func getVersionAPIClient(address string) (protoversion.APIClient, error) {
	clientConn, err := grpc.Dial(address, grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	return protoversion.NewAPIClient(clientConn), nil
}
开发者ID:sammath,项目名称:pachyderm,代码行数:7,代码来源:cmd.go

示例13: main

func main() {
	flag.Parse()

	commits, err := parsePostReceiveRequest(os.Stdin)
	if err != nil {
		panic(err)
	}

	conn, err := grpc.Dial(*address)
	if err != nil {
		glog.Errorf("Cannot dial the master %s: %s", *address, err)
		return
	}
	defer conn.Close()

	client := pb.NewChangeSourceClient(conn)

	reqs, err := createRequestsFromCommits(*gitRepoPath, *projectName, commits)
	if err != nil {
		panic(err)
	}

	for _, req := range reqs {
		_, err = client.Notify(context.Background(), req)
		if err != nil {
			glog.Errorf("Failed to notify the master: %s", err)
			return
		}
		glog.Infof("Notified the master (at %s) successfully", *address)
	}
}
开发者ID:swisscoders,项目名称:gobuilder,代码行数:31,代码来源:postreceive.go

示例14: main

func main() {
	go startDebug()

	addr := os.Args[1]

	conn, err := grpc.Dial(addr, grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()
	log.Print("connected")

	cl := test.NewFooClient(conn)
	barClient, err := cl.Bar(context.Background())
	if err != nil {
		log.Fatalf("calling Bar: %v", err)
	}

	// Comment this out and watch it periodically fail.
	if err := barClient.Send(&test.Outgoing{}); err != nil {
		log.Fatalf("sending: %v", err)
	}

	_, err = barClient.Recv()
	if err != nil {
		log.Fatalf("receiving: %v", err)
	}
}
开发者ID:dpetersen,项目名称:headerbug,代码行数:28,代码来源:main.go

示例15: GetClient

// GetClient attempts to dial the specified address flag and returns a service
// client and its underlying connection. If it is unable to make a connection,
// it dies.
func GetClient() (*grpc.ClientConn, pb.BookServiceClient) {
	conn, err := grpc.Dial(*address, grpc.WithTimeout(5*time.Second), grpc.WithInsecure())
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	return conn, pb.NewBookServiceClient(conn)
}
开发者ID:qaz1243qaz,项目名称:io2015-codelabs,代码行数:10,代码来源:client.go


注:本文中的google/golang.org/grpc.Dial函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。