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

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:

cs 复制代码
    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

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:

cs 复制代码
    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();
        }
    }
相关推荐
走在考研路上41 分钟前
Python错误处理
开发语言·python
数据小爬虫@1 小时前
Python爬虫:如何优雅地“偷窥”商品详情
开发语言·爬虫·python
CV大法好1 小时前
刘铁猛p3 C# 控制台程序引用System.Windows.Forms报错,无法引用程序集 解决方法
开发语言·c#
Days20501 小时前
uniapp小程序增加加载功能
开发语言·前端·javascript
朱小勇本勇2 小时前
Qt实现控件拖曳
开发语言·数据库·qt
VinciYan2 小时前
C#中通过ObjectPool重用对象提高程序性能
c#·asp.net·.net·.netcore
片片叶2 小时前
C++(十四)
开发语言·c++
dengjiayue2 小时前
golang实现简单的reids服务2
开发语言·golang
疯狂的沙粒2 小时前
JavaScript 单例模式的创建与应用
开发语言·前端·javascript·vue.js