一、初步使用
1.vs创建grpc项目
2.服务端
greet.proto
syntax = "proto3"; option csharp_namespace = "GrpcService1"; package greet; // The greeting service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply); } // The request message containing the user's name. message HelloRequest { string name = 1; } // The response message containing the greetings. message HelloReply { string message = 1; }
GreeterService.cs
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) { return Task.FromResult(new HelloReply { Message = "Hello " + request.Name }); } }
Startup.cs
app.UseEndpoints(endpoints => { endpoints.MapGrpcService<GreeterService>(); endpoints.MapGet("/", async context => { await context.Response.WriteAsync("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"); }); });
3.客户端
服务端目前都是现成了,直接写客户端
创建一个控制台,引入
Grpc.Net.Client
Google.Protobuf
Grpc.Tools
4.拷贝服务端的greet.proto到客户端
5.编译proto
右键属性-生成操作
然后手动重新编译一下
6.写客户端代码
using Grpc.Net.Client; using GrpcService1; using System; namespace ConsoleApp2 { class Program { static void Main(string[] args) { var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Greeter.GreeterClient(channel); HelloRequest helloRequest = new HelloRequest(); helloRequest.Name = "Tom"; HelloReply helloReply = new HelloReply(); helloReply=client.SayHello(helloRequest); Console.WriteLine(helloReply.Message); } } }
二、