.netcore grpc截止时间和取消详解

news/2024/5/19 22:25:56 标签: .netcore, rpc, c#

一、截止时间概述

  1. 截止时间功能让 gRPC 客户端可以指定等待调用完成的时间。
  2.  超过截止时间时,将取消调用。
  3.  设定一个截止时间非常重要,因为它将提供调用可运行的最长时间。
  4. 它能阻止异常运行的服务持续运行并耗尽服务器资源。
  5. 截止时间对于构建可靠应用非常有效,应该进行配置。

二、取消概述

  1. 客户端主动取消不再需要长期运行的调用
  2. 线程故障自动取消
  3. 超出截止时间触发取消操作

三、实战案例

  1. 首先准备一个grpc后端服务
  2. 其次准备一个webapi服务作为客户端,方便HttpContext传递
  3. 客户端工厂配置EnableCallContextPropagation 用于上下文传递截止时间
  4. 传递CancellationTokenSource
  5. 话不多说,通过代码可以更好的看出程序的运行轨迹
// 引入proto文件
// 公共messages.proto

syntax = "proto3";

option csharp_namespace = "GrpcProject";

package grpc.serviceing;

// 请求体
message ServerRequest{
	string name = 1;
	double height = 2;
	int32 age = 3;
	bool flag = 4;
	float x = 5;
	float y = 6;
	float z= 7;
	repeated string departments = 8;
}

message ServerFileRequest{
	bytes fileBytes = 1;
}

// 响应体
message ServerResponse{
	bool result = 1;
}


// 服务dollar.proto文件

syntax = "proto3";

import "google/protobuf/empty.proto";
import "Protos/messages.proto";

option csharp_namespace = "GrpcProject";

package grpc.serviceing;

service DollarRpc{
	rpc ServerOne (ServerRequest) returns (ServerResponse);
	rpc ServerTwo (ServerRequest) returns (google.protobuf.Empty);
}


服务端接口实现:

   public class DollarService : DollarRpc.DollarRpcBase
    {
        public override async Task<ServerResponse> ServerOne(ServerRequest request, ServerCallContext context)
        {
            await Console.Out.WriteLineAsync("-------------------------ServerOne------------------------------\r\n");

            await Task.Delay(TimeSpan.FromSeconds(8), context.CancellationToken);

            foreach (var prop in request.GetType().GetProperties())
            {
                await Console.Out.WriteLineAsync($"property  name:{prop.Name};value:{prop.GetValue(request)}");
            }

            return GetResponse();
        }

        public override async Task<Empty> ServerTwo(ServerRequest request, ServerCallContext context)
        {
            await Console.Out.WriteLineAsync("-------------------------ServerTwo------------------------------\r\n");

            await Task.Delay(TimeSpan.FromSeconds(8), context.CancellationToken);
            foreach (var prop in request.GetType().GetProperties())
            {
                await Console.Out.WriteLineAsync($"property  name:{prop.Name};value:{prop.GetValue(request)}");
            }

            return new();
        }

        private ServerResponse GetResponse() => new() { Result = true };
    }

客户端实现重点:

  1. program注入客户端工厂并启用截止时间配置
  2. 增加拦截器统一设定超时时间
  3. 调用查看结果
// program.cs

builder.Services.AddGrpcClient<DollarRpc.DollarRpcClient>(options =>
{
    options.Address = new Uri("https://localhost:7188");
}).EnableCallContextPropagation();
//拦截器过滤截止时间

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class GrpcFilterAttribute : Attribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            CancellationTokenSource tokenSource = new();
            GrpcServerCallContextFeature callContext = new(DateTime.UtcNow.AddSeconds(5), tokenSource.Token);
            context.HttpContext.Features.Set<IServerCallContextFeature>(callContext);
        }
    }

    public class GrpcServerCallContextFeature : ServerCallContext, IServerCallContextFeature
    {
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="deadline"></param>
        /// <param name="cancellationToken"></param>
        public GrpcServerCallContextFeature(DateTime deadline, CancellationToken cancellationToken)
        {
            DeadlineCore = deadline;
            CancellationTokenCore = cancellationToken;
            AuthContextCore = new AuthContext(null, new Dictionary<string, List<AuthProperty>>());
        }

        public ServerCallContext ServerCallContext => this;

        protected override string MethodCore { get; }

        protected override string HostCore { get; }

        protected override string PeerCore { get; }

        protected override DateTime DeadlineCore { get; }

        protected override Metadata RequestHeadersCore { get; }

        protected override CancellationToken CancellationTokenCore { get; }

        protected override Metadata ResponseTrailersCore { get; }

        protected override Status StatusCore { get; set; }

        protected override WriteOptions? WriteOptionsCore { get; set; }

        protected override AuthContext AuthContextCore { get; }

        protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options)
        {
            return base.CreatePropagationToken(options);
        }
        protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders)
        {
            throw new NotImplementedException();
        }
    }
//调用
// 在相应的类上打上标记   [GrpcFilter]

    [Route("api/[controller]")]
    [ApiController]
    [GrpcFilter] // 设定截止时间过滤
    public class GrpcTestController : ControllerBase
    {
        private readonly DollarRpc.DollarRpcClient _dollarRpcClient;

        public GrpcTestController(DollarRpc.DollarRpcClient dollarRpcClient) => _dollarRpcClient = dollarRpcClient;

        [HttpGet("one")]
        public async Task<string> GetOneResult()
        {
            ServerRequest request = new ServerRequest()
            {
                Departments = {
                "one","two","three","four","five"
                },
                Age = 10,
                Flag = true,
                Height = 10,
                Name = "zhangsan",
                X = 10F,
                Y = 11F,
                Z = 12F
            };

            try
            {
                var response = await _dollarRpcClient.ServerOneAsync(request);
                if (response.Result)
                {
                    return "Success";
                }
                return "Fail";
            }
            catch (RpcException ex) when (ex.StatusCode == Grpc.Core.StatusCode.DeadlineExceeded)
            {
                return "dealine timeout.";
            }
            catch (RpcException ex)
            {
                return ($"NoResult:{ex.Message}");
            }
        }

        [HttpGet("two")]
        public async Task<string> GetTwoResult()
        {
            ServerRequest request = new ServerRequest()
            {
                Departments = {
                "one","two","three","four","five"
                },
                Age = 10,
                Flag = true,
                Height = 10,
                Name = "zhangsan",
                X = 10F,
                Y = 11F,
                Z = 12F
            };

            try
            {
                var response = await _dollarRpcClient.ServerTwoAsync(request);
                return "Success";
            }
            catch (RpcException ex) when (ex.StatusCode == Grpc.Core.StatusCode.DeadlineExceeded)
            {
                return "dealine timeout.";
            }
            catch (RpcException ex)
            {
                return ($"NoResult:{ex.Message}");
            }
        }
    }

四、查看执行结果

服务端One:

客户端One:

 

 swagger:

 另一个Two效果类似。同时服务端任务取消错误,也在截图上有显示。

五、源码地址

链接:https://pan.baidu.com/s/1vleChFc3F6ILs-5ad8xQCA 
提取码:mud0


http://www.niftyadmin.cn/n/4971815.html

相关文章

css滚动条样式这样修改下很漂亮

<!DOCTYPE html> <html> <head> <meta charset"utf-8"> <title>滚动条样式修改下很漂亮(不支持IE)</title> <style type"text/css"> * { margin: 0; padding: 0; } .box { width: 300px; height: 100px; margin…

快速理解 X server, DISPLAY 与 X11 Forwarding

​ X server X server是X Window System &#xff08;简称X11或者X&#xff09;系统中的显示服务器&#xff08;display server&#xff09;&#xff0c;用于监听X client发送来的图形界面显示请求&#xff0c;并且将图形界面渲染并显示在屏幕&#xff08;screen&#xff09;…

ctfshow-web13 文件上传

0x00 前言 CTF 加解密合集CTF Web合集 0x01 题目 0x02 Write Up 首先看到是一个上传页面&#xff0c;测试其他无果&#xff0c;遂进行目录遍历&#xff0c;发现upload.php.bak文件 可以看到这里的限制条件&#xff0c;大小&#xff0c;以及内容&#xff0c;这里可以使用.use…

R语言画样本不均衡组的箱线图

# 导入 ggplot2 包 library(ggplot2)# 示例数据框&#xff0c;包含数值数据和分组信息 data <- data.frame(Group c(rep("Group A",10), rep("Group B",15),rep("Group C",20)),Value c(rnorm(10, mean 10, sd 2),rnorm(15, mean 15, sd…

如何使用 try-with-resources 优雅地关闭资源

今天学习下Java 7中引入的try-with-resources语法糖&#xff0c;一个非常有用的特性&#xff0c;它使得在代码中使用资源&#xff08;例如文件或数据库连接&#xff09;变得更加简单、方便和安全。所有被打开的系统资源&#xff0c;比如流、文件或者Socket连接等&#xff0c;都…

numpy高级函数之where和extract函数

1 numpy.where() 函数返回输入数组中满足给定条件的元素的索引 ---------------------------------------------------- 代码&#xff1a; n1np.random.randint(10,20,10) n2np.where(n1>15) 结果&#xff1a; [17 15 19 15 12 10 16 11 15 13] #原始数组 (array([…

C# 实现 国密SM4/ECB/PKCS7Padding对称加密解密

C# 实现 国密SM4/ECB/PKCS7Padding对称加密解密&#xff0c;为了演示方便本问使用的是Visual Studio 2022 来构建代码的 1、新建项目&#xff0c;之后选择 项目 鼠标右键选择 管理NuGet程序包管理&#xff0c;输入 BouncyCastle 回车 添加BouncyCastle程序包 2、代码如下&am…

Redis之GEO类型解读

目录 基本介绍 基本命令 geoadd 命令 geopos 命令 geodist 命令 georadius 命令 georadiusbymember 命令 geohash 命令 基本介绍 GEO 主要用于存储地理位置信息&#xff08;纬度、经度、名称&#xff09;添加到指定的key中。该功能在 Redis 3.2 版本新增。 GEO&…