Reputation: 41
I have read the document and I don't see the details that when I make a unary call to grpc server, I create a new client or reuse a client (Channel will obviously reuse it again). As the code below, use SayHello or SayHello1. Thank you.
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;
}
}
}
Upvotes: 4
Views: 1312
Reputation: 6092
From https://learn.microsoft.com/en-us/aspnet/core/grpc/performance?view=aspnetcore-7.0
A gRPC channel should be reused when making gRPC calls. Reusing a channel allows calls to be multiplexed through an existing HTTP/2 connection.
gRPC clients are created with channels. gRPC clients are lightweight objects and don't need to be cached or reused.
Upvotes: 0
Reputation: 1653
Most commonly, you would reuse the same client class instance ("GreeterClient" in your case) for all calls you make. That said, creating a new "GreeterClient" instance (from a pre-existing channel) is a very cheap operation, so creating more instances of client class (e.g. due to logical structure of your code) doesn't do any harm.
Channel class is comparably much more heavyweight and you should only be creating new channel instances when you have a good reason to do so.
Upvotes: 3