前言:

gRPC默认是ProtoFirst的,即先写 proto文件,再生成代码,需要人工维护proto,生成的代码也不友好,所以出现了gRPC CodeFirst,下面来说说我们是怎么实现gRPC CodeFirst

目录:

实现和WCF一样的CodeFirst

(1). 实现gRPC CodeFirst,  简化WCF一定要抽取接口的问题

(2). 通过代码生成proto和注释,给第三方语言使用

(3). 实现gRPC DashBoard,用于Http远程调用和管理

(4). 实现gRPC scope注入的三种方式(asp.net core3.0 grpc默认是scope)

(5). 实现服务注册与发现

(6). 实现分布式日志跟踪

(7). 日志监控等等

我们是怎么实现gRPC CodeFirst

1.要实现CodeFirst先要了解ProtoFirst生成的代码,下面我截了部分生成代码

(1).关键是这个BindService,用于把实现的gRPC方法绑定到ServerServiceDefinition

public static partial class Greeter
{
static readonly string __ServiceName = "helloworld.Greeter"; static readonly grpc::Marshaller<global::Helloworld.HelloRequest> __Marshaller_helloworld_HelloRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Helloworld.HelloRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Helloworld.HelloReply> __Marshaller_helloworld_HelloReply = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Helloworld.HelloReply.Parser.ParseFrom); static readonly grpc::Method<global::Helloworld.HelloRequest, global::Helloworld.HelloReply> __Method_SayHello = new grpc::Method<global::Helloworld.HelloRequest, global::Helloworld.HelloReply>(
grpc::MethodType.Unary,
__ServiceName,
"SayHello",
__Marshaller_helloworld_HelloRequest,
__Marshaller_helloworld_HelloReply); static readonly grpc::Method<global::Helloworld.HelloRequest, global::Helloworld.HelloReply> __Method_SayHelloStream = new grpc::Method<global::Helloworld.HelloRequest, global::Helloworld.HelloReply>(
grpc::MethodType.ClientStreaming,
__ServiceName,
"SayHelloStream",
__Marshaller_helloworld_HelloRequest,
__Marshaller_helloworld_HelloReply); /// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(GreeterBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_SayHello, serviceImpl.SayHello)
.AddMethod(__Method_SayHelloStream, serviceImpl.SayHelloStream).Build();
} /// <summary>Register service method with a service binder with or without implementation. Useful when customizing the service binding logic.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary>
/// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static void BindService(grpc::ServiceBinderBase serviceBinder, GreeterBase serviceImpl)
{
serviceBinder.AddMethod(__Method_SayHello, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Helloworld.HelloRequest, global::Helloworld.HelloReply>(serviceImpl.SayHello));
serviceBinder.AddMethod(__Method_SayHelloStream, serviceImpl == null ? null : new grpc::ClientStreamingServerMethod<global::Helloworld.HelloRequest, global::Helloworld.HelloReply>(serviceImpl.SayHelloStream));
}
}

(2).__Marshaller_helloworld_HelloRequest这个是实现protobuffer的序列化和反序列化的一个委托

服务的请求参数和返回参数,我们使用Protobuf-net来实现序列化和反序列化,和 WCF一样需要给类打上标签

    /// <summary>
/// 加法请求参数
/// </summary>
[ProtoContract]
public class AddRequest
{
/// <summary>
/// 第一个数字
/// </summary>
[ProtoMember(1)]
public int Num1 { get; set; } /// <summary>
/// 第二个数字
/// </summary>
[ProtoMember(2)]
public int Num2 { get; set; }
}

2.要实现CodeFirst需要实现这个BindService,把我们的Grpc方法添加到ServerServiceDefinition

(1).我们让Grpc服务实现IGrpcService空接口,用于标识是GrpcService

    /// <summary>
/// MathGrpc
/// </summary>
public class MathGrpc : IGrpcService
{
/// <summary>
/// 加法
/// </summary>
/// <param name="request"></param>
/// <param name="context"></param>
/// <returns></returns>
public Task<IntMessage> Add(AddRequest request, ServerCallContext context)
{
var result = new IntMessage();
result.Value = request.Num1 + request.Num2;
return Task.FromResult(result);
}
}

(2).获取实现了IGrpcService接口的类,然后反射获取方法,再添加到ServerServiceDefinition即可

这里调用了GrpcMethodHelper.AutoRegisterMethod()方法,这是通过反射自动注册GrpcMethod的方法

        /// <summary>
/// 注入IGrpcService
/// </summary>
/// <param name="grpcServices"></param>
/// <returns></returns>
private ServerBuilder UseGrpcService(IEnumerable<IGrpcService> grpcServices)
{
var builder = ServerServiceDefinition.CreateBuilder();
grpcServices.ToList().ForEach(grpc => GrpcMethodHelper.AutoRegisterMethod(grpc, builder));
_serviceDefinitions.Add(builder.Build());
return this;
}

未完,待续,欢迎评论拍砖

这些功能早在2018年就已经实现并运行在生产,感兴趣的同学可以去 github上查看,你要的都有,欢迎提issue

我们是怎么实现Grpc CodeFirst的更多相关文章

  1. 我们是怎么实现gRPC CodeFirst-生成proto

    前言: gRPC默认是ProtoFirst的,即先写 proto文件,再生成代码,需要人工维护proto,生成的代码也不友好,所以出现了gRPC CodeFirst,下面来说说我们是怎么实现gRPC ...

  2. .NET Core 3.0中用 Code-First 方式创建 gRPC 服务与客户端

    .NET Core love gRPC 千呼万唤的 .NET Core 3.0 终于在 9 月份正式发布,在它的众多新特性中,除了性能得到了大大提高,比较受关注的应该是 ASP.NET Core 3. ...

  3. MVC5+EF6+MYSQl,使用codeFirst的数据迁移

    之前本人在用MVC4+EF5+MYSQL搭建自己的博客.地址:www.seesharply.com;遇到一个问题,就是采用ef的codefirst模式来编写程序,我们一般会在程序开发初期直接在glob ...

  4. MVC CodeFirst简单的创建数据库(非常详细的步骤)

       最近在学习MVC的开发,相信有过开发经验的人初学一个新的框架时候的想法跟我一样最关心的就是这个框架如何架构,每个架构如何分工,以及最最关键的就是如何与数据库通信,再下来才是学习基础的页面设计啊等 ...

  5. ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存

    ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存 part 1:给我点时间,允许我感慨一下2016年 正好有时间,总结一下最近使用的一些技术,也算是为2016年画上一个完 ...

  6. 使用EF CodeFirst 创建数据库

    EntityFramework 在VS2015添加新建项时,选择数据->ADO.NET 实体数据模型,有一下选项 来自数据库的EF设计器,这个就是我们最常用的EntityFramework设计模 ...

  7. gRPC源码分析1-SSL/TLS

    引子 前几天看到微信后台团队分享了TLS相关文章,正好gRPC里TLS数据加密是很重要的一块,于是整理出了这篇文章. 在gRPC里,如果仅仅是用来做后端微服务,可以考虑不加密.本文太长,先给个大纲. ...

  8. 1.【使用EF Code-First方式和Fluent API来探讨EF中的关系】

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/relationship-in-entity-framework-using-code-firs ...

  9. 2.EF中 Code-First 方式的数据库迁移

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/code-first-migrations-with-entity-framework/ 系列目 ...

随机推荐

  1. ES常见问题整理

    1.集群状态red.yellow处理方法 1.red表示主分片数据不完整,通常时由于某个索引的主分片为分片unassigned,找出这个分片未分配的原因,解决即可: curl -XGET http:/ ...

  2. mysql5.6和5.7的权限密码设置

    mysql5.6grant all privileges on *.* to root@'%' identified by "mysql_pwd" with grant optio ...

  3. ubuntu 18.04用apt安装mysql-server

    mysql5.7安装完成后普通用户不能进mysql 原因:root的plugin被修改成了auth_socket,用密码登陆的plugin应该是mysql_native_password,直接用roo ...

  4. IP不是万能药 为何有蜘蛛侠等大片的索尼要放弃电影

    ​ 为何有蜘蛛侠等大片的索尼要放弃电影"> 近年来,国内狂炒"IP"这一概念,比如动漫.网络文学.小说.游戏等,甚至围绕IP制造出内容矩阵.从一个IP延伸至多个领域 ...

  5. Git pull 卡在Unpacking objects

    今天在拉取远程仓库的时候在Unpacking objects阶段 进度条卡住,不知道什么原因. 翻取相关资料搜索后得知:在拉取大型二进制对象(如Adobe Illustrator文件等)可能会使整个拉 ...

  6. Spark基础全解析

    我的个人博客:https://www.luozhiyun.com/ 为什么需要Spark? MapReduce的缺陷 第一,MapReduce模型的抽象层次低,大量的底层逻辑都需要开发者手工完成. 第 ...

  7. swagger 以及swaggerUI使用的步骤

    1.swagger,可以这么理解swagger是接口规范.Rest Api 传递参数的除了get请求外,put post,需要传递json.或者就是直接都通过传递json到后台 这里主要介绍一下spr ...

  8. Roma - Facebook工具链大一统

    什么是roma roma,中文名罗马,是Facebook的rn团队的产出,是一个试验性质的javascript工具链,集编译,linter,格式化,打包,测试等等于一体.目标是成为一个处理javasc ...

  9. SQL语句中in 与 exists的区别

    SQL语句中in 与 exists的区别 SQL中EXISTS检查是否有结果,判断是否有记录,返回的是一个布尔型(true/false); IN是对结果值进行比较,判断一个字段是否存在于几个值的范围中 ...

  10. 前端javascript知识(三)

    函数记忆,判断是不是质数. 方法一: function isPrime1(n){ if(n<=3){return true} else{ for(var i=2;i<Math.sqrt(n ...