c# Grpc取消
net6.0
通过CancellationTokenSource 客户端取消Grpc,服务端判断 IsCancellationRequested 是否取消。
proto:
syntax = "proto3";
// 引用可空类型
import "google/protobuf/wrappers.proto";
option csharp_namespace = "Grpc.Common";
package greet;
// The greeting service definition.
service Greeter {
rpc StreamApi (HelloRequest) returns (stream HelloResponse);
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
message HelloResponse {
string message = 1;
}
服务端:
nuget包:Grpc.AspNetCore、Grpc.AspNetCore.Server.Reflection
GreeterService.cs
using Grpc.Core;
using Grpc.Common;
public class GreeterService : Greeter.GreeterBase
{
private readonly ILogger<GreeterService> _logger;
public GreeterService(ILogger<GreeterService> logger)
{
_logger = logger;
}
public override async Task StreamApi(HelloRequest request, IServerStreamWriter<HelloResponse> responseStream, ServerCallContext context)
{
try
{
for (var i = 0; i < 50; i++)
{
if (context.CancellationToken.IsCancellationRequested)
{
await responseStream.WriteAsync(new HelloResponse
{
Message = i.ToString()
});
await Task.Delay(1000 * 3);
}
}
}
catch (OperationCanceledException ex)
{
throw;
}
}
}
program:
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Additional configuration is required to successfully run gRPC on macOS.
// For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
// Add services to the container.
builder.Services.AddGrpc();
builder.Services.AddGrpcReflection();//添加gRPC反射
var app = builder.Build();
IWebHostEnvironment env = app.Environment;
// Configure the HTTP request pipeline.
app.MapGrpcService<GreeterService>();
if (env.IsDevelopment())
{
//映射gRPC反射服务
app.MapGrpcReflectionService();
}
app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
app.Run();
}
}
客户端:
nuget包:Google.Protobuf、Grpc.Net.Client、Grpc.Net.ClientFactory、Grpc.Tools
GreeterService.cs
public class GreeterService
{
private readonly GreeterClient _greeterClient;
public GreeterService(GreeterClient greeterClient)
{
_greeterClient = greeterClient;
}
private static CancellationTokenSource ProbeLoopCancellationTokenSource = new CancellationTokenSource();
public async Task StreamApiAsync(HelloRequest request)
{
using var call = _greeterClient.StreamApi(request, cancellationToken: ProbeLoopCancellationTokenSource.Token);
await foreach (var response in call.ResponseStream.ReadAllAsync())
{
Console.WriteLine(response.Message);
}
}
public async Task CancleAsync()
{
ProbeLoopCancellationTokenSource.Cancel();
}
}
program:
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<GreeterService>();
builder.Services.AddGrpcClient<GreeterClient>(options =>
{
options.Address = new Uri("http://localhost:5047");
options.ChannelOptionsActions.Add(channelOption =>
{
channelOption.HttpHandler = new SocketsHttpHandler
{
EnableMultipleHttp2Connections = true
};
});
//配置请求超时自动取消时间 发起请求到服务端后xxx秒后自动取消
//options.CallOptionsActions.Add(callOptionsAction =>
//{
// callOptionsAction.CallOptions = new CallOptions(deadline: DateTime.UtcNow.AddSeconds(xx));
//});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
原文地址:https://blog.csdn.net/czjnoe/article/details/144268226
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!