3

我已阅读文档,但没有看到当我对 grpc 服务器进行一元调用时,我创建一个新客户端或重用客户端(Channel 显然会再次重用它)的详细信息。如下代码,使用 SayHello 或 SayHello1。谢谢你。

using System;
using Grpc.Core;
using HelloWorld;

namespace GreeterClient
{
    class Program
    {
        static Greeter.GreeterClient client;
        static Channel channel;
        public static void Main(string[] args)
        {
            channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);
            client = new Greeter.GreeterClient(channel);

            while (true)
            {
                try
                {
                    var name = Console.ReadLine();
                    var reply = SayHello(name);
                    Console.WriteLine(reply);
                }
                catch (RpcException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            channel.ShutdownAsync().Wait();

        }
        public static string SayHello(string name)
        {
            var reply = client.SayHello(new HelloRequest { Name = name });
            return reply.Message;
        }
        public static string SayHello1(string name)
        {
            var newClient = new Greeter.GreeterClient(channel);
            var reply = newClient.SayHello(new HelloRequest { Name = name });
            return reply.Message;
        }
    }
}
4

1 回答 1

3

最常见的是,您会为您进行的所有调用重用相同的客户端类实例(在您的情况下为“GreeterClient”)。也就是说,创建一个新的“GreeterClient”实例(从一个预先存在的通道)是一个非常便宜的操作,所以创建更多的客户端类实例(例如由于你的代码的逻辑结构)不会造成任何伤害。

Channel 类相对来说要重得多,只有在有充分理由时才应该创建新的通道实例。

于 2019-04-11T09:32:55.060 回答