gpt4 book ai didi

c# - 为什么 gRPC 不维护服务方法调用之间的状态?

转载 作者:行者123 更新时间:2023-12-05 07:07:21 24 4
gpt4 key购买 nike

下面是我的原型(prototype)服务:

service Greeter {
// Sends a greeting
rpc IntroduceYourName(HelloRequest) returns (google.protobuf.Empty);
rpc SayHellos (RepeatHelloRequest) returns (stream HelloReply);
}

// The request message containing the user's name.
message HelloRequest {
string name = 1;
}

message RepeatHelloRequest {
int32 count = 1;
}


// The response message containing the greetings.
message HelloReply {
string message = 1;
}

这是一个简单的服务,我试图在 IntroduceYourName 方法中设置 Name 属性,并在 SayHellos 方法中取回 Name。

但是,当客户端调用SayHellos 方法时,它不起作用,Name 为空。

我正在研究 Net Core 3.1。

服务器实现:

public override Task<Empty> IntroduceYourName(HelloRequest request, ServerCallContext context)
{
this.Name = request.Name;
_logger.LogInformation($"Name : {this.Name}");
return Task.FromResult(new Empty());
}

public override async Task SayHellos(RepeatHelloRequest request, IServerStreamWriter<HelloReply> responseStream, ServerCallContext context)
{
logger.LogInformation($"SayHellos Name : {this.Name}");
// _logger.LogInformation("SayRepeatHello called");
int i = 0;
while (!context.CancellationToken.IsCancellationRequested && i++ < request.Count)
{
var reply = new HelloReply
{
Message = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt") + $" Hello {i} " +this.Name
};
await responseStream.WriteAsync(reply);
await Task.Delay(1000);
}
if (context.CancellationToken.IsCancellationRequested)
{
_logger.LogInformation("The client cancelled their request");
}
}

客户端代码:

using var channel = GrpcChannel.ForAddress("https://localhost:5001");
CancellationToken ct = new CancellationToken();
Greeter.GreeterClient client = new Greeter.GreeterClient(channel);
client.IntroduceYourName(new HelloRequest() { Name = "Foo" });

using var stream = client.SayHellos(new RepeatHelloRequest() { Count = 10 }, cancellationToken: ct);
while (await stream.ResponseStream.MoveNext(ct))
{
Console.WriteLine("Greeting: " + stream.ResponseStream.Current.Message);
}

最佳答案

那是因为 .net core 的 IoC 容器在服务器端为每个 gRPC GreeterService 创建了新的实例。因此,您应该告诉 IoC 将您的 gRPC 服务视为单例。将以下内容添加到服务器的 Startup.cs。

    public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc();
services.AddSingleton<GreeterService>();
}

归功于 this SO post

关于c# - 为什么 gRPC 不维护服务方法调用之间的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62188598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com