首页 > 其他分享 >protobuf-net.Grpc 笔记

protobuf-net.Grpc 笔记

时间:2024-07-12 17:43:46浏览次数:17  
标签:set protobuf get Grpc net public string

众所周知,Grpc很好用,但每次都需要手动编写 *.proto 文件,protobuf-net.Grpc个人感觉最大的优势是不用写*.proto 文件,相关教程如下:

https://learn.microsoft.com/zh-cn/aspnet/core/grpc/code-first?view=aspnetcore-8.0

https://protobuf-net.github.io/protobuf-net.Grpc/gettingstarted

https://github.com/protobuf-net/protobuf-net.Grpc  
1. 定义代码协定
创建类库,名称为ProtobufNetShared,安装 protobuf-net.Grpc 和 System.ServiceModel.Primitives

[ServiceContract]
public interface IGreeterService
{
    [OperationContract]
    Task<HelloReply> SayHelloAsync(HelloRequest request);
}

[DataContract]
public class HelloRequest
{
    [DataMember(Order = 1)]
    public string Name { get; set; }
}

[DataContract]
public class HelloReply 
{
    [DataMember(Order = 1)]
    public string Message { get; set; }
}

[Service]
public interface IOrderService
{
    CreateResult CreateOrder(CreateRequest request);
    QueryResult QueryOrder(QueryRequest request);
}

[ProtoContract]
public class CreateRequest
{
    [ProtoMember(1)]
    public string OrderNo { get; set; }

    [ProtoMember(2)]
    public string OrderName { get; set; }

    [ProtoMember(3)]
    public string Price { get; set; }
}

[ProtoContract]
public class CreateResult
{
    [ProtoMember(1)]
    public bool Result { get; set; }

    [ProtoMember(2)]
    public string Message { get; set; }
}

[ProtoContract]
public class QueryRequest
{
    [ProtoMember(1)]
    public int Id { get; set; }
}

[ProtoContract]
public class QueryResult
{
    [ProtoMember(1)]
    public int Id { get; set; }

    [ProtoMember(2)]
    public string OrderNo { get; set; }

    [ProtoMember(3)]
    public string OrderName { get; set; }

    [ProtoMember(4)]
    public double Price { get; set; }
}

前面的代码,SayHello 部分定义了HelloRequest、HelloReply消息 和 使用一元 SayHelloAsync gRPC 方法定义 IGreeterService 协定接口

代码如下:https://gitee.com/Karl_Albright/csharp-demo/tree/master/GrpcDemo/ProtobufNetShared

 

2. 定义Grpc服务

创建 ASP.NET Core Web API 项目,名称为ProtobufNetService,安装 protobuf-net.Grpc.AspNetCore 和 引用 ProtobufNetShared

 创建 GreeterService 并实现 IGreeterService,创建 OrderService 并实现 IOrderService

public class GreeterService : IGreeterService
{
    public Task<HelloReply> SayHelloAsync(HelloRequest request)
    {
        return Task.FromResult(new HelloReply 
        {
            Message = "你好 " + request.Name
        });
    }
}
public class OrderService : IOrderService
{
    public CreateResult CreateOrder(CreateRequest request)
    {
        return new CreateResult
        {
            Result = true,
            Message = "订单创建成功",
        };
    }

    public QueryResult QueryOrder(QueryRequest request)
    {
        return new QueryResult 
        {
            Id = request.Id,
            OrderNo = DateTime.Now.ToString("yyyyMMddHHmmss"),
            OrderName = "冰箱",
            Price = 1288
        };
    }
}

更新 Program 文件 

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        builder.Services.AddCodeFirstGrpc();

        var app = builder.Build();

        app.MapGrpcService<GreeterService>();

        app.MapGrpcService<OrderService>();

        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();
    }
}
AddCodeFirstGrpc 注册启用了代码优先的服务。 MapGrpcService<GreeterService> 添加代码优先的服务终结点 appsettings.json配置中增加http2配置

代码如下:https://gitee.com/Karl_Albright/csharp-demo/tree/master/GrpcDemo/ProtobufNetService  
3. 创建 Grpc客户端

创建控制台项目,名称叫 ProtobufNetDemo,安装 Grpc.Net.Client 和 protobuf-net.Grpc

 更新 Program.cs 代码

internal class Program
{
    static async Task Main(string[] args)
    {
        using var channel = GrpcChannel.ForAddress("http://localhost:5041");
        var client = channel.CreateGrpcService<IGreeterService>();
        var reply = await client.SayHelloAsync(
        new HelloRequest { Name = "Karl" });

        Console.WriteLine($"Greeting: {reply.Message}");
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
}

代码如下:https://gitee.com/Karl_Albright/csharp-demo/tree/master/GrpcDemo/ProtobufNetDemo

先运行 ProtobufNetService,再运行 ProtobufNetDemo 运行结果如下 

 

4. 创建 Web api 客户端

 创建 ASP.NET Core Web API 项目,名称为ProtobufNetClient,安装 protobuf-net.Grpc.AspNetCore、protobuf-net.Grpc.ClientFactory 和 引用 ProtobufNetShared

 增加 Program.cs 代码

builder.Services.AddCodeFirstGrpcClient<IGreeterService>(o =>
{
    o.Address = new Uri("http://localhost:5041/");
    o.ChannelOptionsActions.Add(options =>
    {
        options.HttpHandler = new SocketsHttpHandler()
        {
            // keeps connection alive
            PooledConnectionIdleTimeout = Timeout.InfiniteTimeSpan,
            KeepAlivePingDelay = TimeSpan.FromSeconds(60),
            KeepAlivePingTimeout = TimeSpan.FromSeconds(30),

            // allows channel to add additional HTTP/2 connections
            EnableMultipleHttp2Connections = true
        };
    });
});
builder.Services.AddCodeFirstGrpcClient<IOrderService>(o =>
{
    o.Address = new Uri("http://localhost:5041/");
    o.ChannelOptionsActions.Add(options =>
    {
        options.HttpHandler = new SocketsHttpHandler()
        {
            // keeps connection alive
            PooledConnectionIdleTimeout = Timeout.InfiniteTimeSpan,
            KeepAlivePingDelay = TimeSpan.FromSeconds(60),
            KeepAlivePingTimeout = TimeSpan.FromSeconds(30),

            // allows channel to add additional HTTP/2 connections
            EnableMultipleHttp2Connections = true
        };
    });
});

创建 HelloController 和 OrderController

[ApiController]
[Route("[controller]/[action]")]
public class HelloController : ControllerBase
{
    IGreeterService service;
    public HelloController(IGreeterService service) 
    {
        this.service = service;
    }

    [HttpGet(Name = "Echo")]
    public string Echo(string name)
    {
        return service.SayHelloAsync(new HelloRequest { Name = name }).Result.Message;
    }
}
[ApiController] [Route("[controller]/[action]")] public class OrderController : ControllerBase { IOrderService service; public OrderController(IOrderService service) { this.service = service; } [HttpGet(Name = "CreateOrder")] public CreateResult CreateOrder() { return service.CreateOrder(new CreateRequest { OrderNo = DateTime.Now.ToString("yyyyMMddHHmmss"), OrderName = "订单名称", Price = "12.32" }); } [HttpGet(Name = "QueryOrder")] public QueryResult QueryOrder(int id) { return service.QueryOrder(new QueryRequest { Id = id, }); } }

代码地址: https://gitee.com/Karl_Albright/csharp-demo/tree/master/GrpcDemo/ProtobufNetClient

先运行 ProtobufNetService,再运行 ProtobufNetClient 运行结果如下,在Swagger中调用相应的Api

 

 

 

 

标签:set,protobuf,get,Grpc,net,public,string
From: https://www.cnblogs.com/KarlAlbright/p/18299056

相关文章

  • Neuralink 将启动第二例人类脑机芯片植入;多项 Claude 3.5 Sonnet AI 工具发布丨RTE 开
      开发者朋友们大家好: 这里是「RTE开发者日报」,每天和大家一起看新闻、聊八卦。我们的社区编辑团队会整理分享RTE(Real-TimeEngagement)领域内「有话题的新闻」、「有态度的观点」、「有意思的数据」、「有思考的文章」、「有看点的会议」,但内容仅代表编辑的个人观点,......
  • 研究gRPC所给的helloworld例子
    这里我以编写一个远程过程调用,客户端传过来请求,远程过程调用就可以返回当前时间。(daytime服务器熟知端口是13,这里并不是搭建daytime,只是为了测试远程过程调用是否成功)CMakeLists.txt文件的编写cmake_minimum_required(VERSION3.8)project(HelloWorldCCXX)include(../cmake/......
  • 在C++中使用gRPC框架
    概览在gRPC里客户端应用可以像调用本地对象一样直接调用另一台不同机器上的服务端应用的方法,使得您能够更容易地创建分布式应用和服务。与许多RPC系统类似,gRPC也是基于以下理念:定义一个服务,指定其能够被远程调用的方法(包括参数和返回类型)。在服务器端实现这个接口,并运行一个gRPC......
  • NET6 通过接口完成自动注入
    根据NETCore的注入方式添加三个接口///<summary>///瞬时注入服务接口///</summary>publicinterfaceITransient{}///<summary>///作用域注入服务接口///</summary>publicinterfaceIScoped{}///<summary>///单例注入服务接口///</summary>public......
  • 全网最全AI绘画 StablDiffusion系列进阶篇-ControlNet插件介绍
    大家好,我是设计师阿威之前,我已经分享了众多AI绘画方面的学习教程文章,对于想自娱自乐的小伙伴们来说,这些内容应该已经足够使用了。但如果你的工作需要更精细的控制,想要达到更专业的水准,那就得进一步使用一些插件工具了。今天,就让我们来简单聊聊StablDiffusion的高级用法-C......
  • 全速增长!NetMarvel 与您相约 2024 ChinaJoy 盛会!
    2024年第二十一届ChinaJoy将于7月26日至29日在上海新国际博览中心盛大召开。继去年成功参展后,全球一站式效果营销服务平台——NetMarvel今年将继续亮相,与您相约W4馆B208展位,共同探讨全球移动互联网行业增长!在如今普遍流量触底的大环境下,出海厂商如何寻找新增量?作为一家在移动......
  • WPF WebBrowser make sure the path or Internet address is correct
      Onepossiblecauseisincludechinesecharacters, //WrongcodeprivatevoidOpenClick(objectsender,RoutedEventArgse){OpenFileDialogdialog=newOpenFileDialog();dialog.Filter="PDFFiles|*.pdf|AllFiles|*.*";i......
  • 编译安装Kubernetes 1.29 高可用集群(9)--Harbor私有仓库部署
    1.环境说明操作系统:openEuler22.03软件版本:harbor2.10.32.Harbor软件安装2.1安装前准备#systemctldisablefirewalld.service#systemctlstopfirewalld.service#sed-i's/SELINUX=enforcing/SELINUX=disabled/'/etc/selinux/config#setenforce0#hostnamec......
  • .NET/C#、Netcore、数据库、Redis 、RabbitMQ&kafka、Docker ⾯试题汇总系列目录
    .NET/C#⾯试题汇总系列.NET/C#⾯试题汇总系列:ASP.NET常见面试题001.NET/C#⾯试题汇总系列:ASP.NET常见面试题002.NET/C#⾯试题汇总系列:ASP.NET常见面试题003.NET/C#⾯试题汇总系列:基础语法.NET/C#⾯试题汇总系列:ASP.NETMVC.NET/C#⾯试题汇总系列:多线程.NET/C#⾯......
  • .NET 9 预览版6发布
    微软发布了.NET9的第6个预览版,此版本包括对运行时、SDK、.NETMAUI、ASP.NETCore和C#的更新,预览版没有包含太多新的主要功能或特性,因为已接近.NET9开发的最后阶段,该开发计划于11月全面发布。Loongarch的Native-AOT代码合进去了,龙芯.NET可以直接同步社区代码,这样龙......