asp.net core grpc快速入门

环境

.net 8

vs2022

创建 gRPC 服务器


一定要勾选Https

安装Nuget包

xml 复制代码
<PackageReference Include="Google.Protobuf" Version="3.28.2" />
<PackageReference Include="Grpc.AspNetCore" Version="2.66.0" />
<PackageReference Include="Grpc.Net.Client" Version="2.66.0" />
<PackageReference Include="Grpc.Tools" Version="2.66.0">
	<PrivateAssets>all</PrivateAssets>
	<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>

新建Protos文件夹,该文件下新建greet.proto

go 复制代码
syntax = "proto3";

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

添加编译

xml 复制代码
<ItemGroup>
  <Protobuf Include="Protos\greet.proto" GrpcServices="Server" />
</ItemGroup>

新建Service文件夹,该文件夹下新建GreeterService

cs 复制代码
using Grpc.Core;

namespace GrpcServer01.Service
{
    public class GreeterService : Greeter.GreeterBase
    {
        private readonly ILogger<GreeterService> _logger;

        public GreeterService(ILogger<GreeterService> logger)
        {
            _logger = logger;
        }

        public override Task<HelloReply> SayHello(HelloRequest request,
            ServerCallContext context)
        {
            _logger.LogInformation("Saying hello to {Name}", request.Name);
            return Task.FromResult(new HelloReply
            {
                Message = "Hello " + request.Name
            });
        }
    }
}

修改Program.cs

cs 复制代码
using GrpcServer01.Service;

namespace GrpcServer01
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            //新增代码在这
            builder.Services.AddGrpc();
            
            var app = builder.Build();
            
            //新增代码在这
            app.MapGrpcService<GreeterService>();
            app.MapGet("/", () => "Hello World!");

            app.Run();
        }
    }
}

启动项目访问https://localhost:7006/

服务端创建成功

创建grpc客户端


安装nuget包

xml 复制代码
<ItemGroup>
	<PackageReference Include="Google.Protobuf" Version="3.28.2" />
	<PackageReference Include="Grpc.Net.Client" Version="2.66.0" />
	<PackageReference Include="Grpc.Tools" Version="2.66.0">
		<PrivateAssets>all</PrivateAssets>
		<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
	</PackageReference>
</ItemGroup>

复制服务端Protos\greet.proto到客户端

xml 复制代码
<ItemGroup>
	<Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
</ItemGroup>

修改Program.cs

cs 复制代码
internal class Program
{
    static async Task Main(string[] args)
    {
        using var channel = GrpcChannel.ForAddress("https://localhost:7006");
        var client = new Greeter.GreeterClient(channel);
        var reply = await client.SayHelloAsync(
                          new HelloRequest { Name = "GreeterClient" });
        Console.WriteLine("Greeting: " + reply.Message);
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
}

客户端

服务端

参考

https://grpc.io/docs/languages/csharp/
https://blog.csdn.net/kevin_tech/article/details/120681720
https://learn.microsoft.com/zh-cn/aspnet/core/grpc/?view=aspnetcore-8.0
grpc详解
https://cloud.tencent.com/developer/article/1913513
https://protobuf.dev/overview/

相关推荐
向前看-36 分钟前
验证码机制
前端·后端
超爱吃士力架2 小时前
邀请逻辑
java·linux·后端
AskHarries4 小时前
Spring Cloud OpenFeign快速入门demo
spring boot·后端
isolusion5 小时前
Springboot的创建方式
java·spring boot·后端
zjw_rp6 小时前
Spring-AOP
java·后端·spring·spring-aop
TodoCoder6 小时前
【编程思想】CopyOnWrite是如何解决高并发场景中的读写瓶颈?
java·后端·面试
凌虚7 小时前
Kubernetes APF(API 优先级和公平调度)简介
后端·程序员·kubernetes
机器之心7 小时前
图学习新突破:一个统一框架连接空域和频域
人工智能·后端
.生产的驴8 小时前
SpringBoot 对接第三方登录 手机号登录 手机号验证 微信小程序登录 结合Redis SaToken
java·spring boot·redis·后端·缓存·微信小程序·maven
顽疲8 小时前
springboot vue 会员收银系统 含源码 开发流程
vue.js·spring boot·后端