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();
        }
    }
相关推荐
xyq20241 小时前
TypeScript中的String类型详解
开发语言
小糖学代码7 小时前
LLM系列:1.python入门:15.JSON 数据处理与操作
开发语言·python·json·aigc
handler017 小时前
从源码到二进制:深度拆解 Linux 下 C 程序的编译与链接全流程
linux·c语言·开发语言·c++·笔记·学习
小白学大数据7 小时前
现代Python爬虫开发范式:基于Asyncio的高可用架构实战
开发语言·爬虫·python·架构
渔舟小调7 小时前
P19 | 前端加密通信层 pikachuNetwork.js 完整实现
开发语言·前端·javascript
不爱吃炸鸡柳8 小时前
数据结构精讲:树 → 二叉树 → 堆 从入门到实战
开发语言·数据结构
网络安全许木8 小时前
自学渗透测试第21天(基础命令复盘与DVWA熟悉)
开发语言·网络安全·渗透测试·php
t***5448 小时前
如何在Dev-C++中使用Clang编译器
开发语言·c++
码界筑梦坊8 小时前
93-基于Python的中药药材数据可视化分析系统
开发语言·python·信息可视化
Cosmoshhhyyy9 小时前
《Effective Java》解读第49条:检查参数的有效性
java·开发语言