平台:dotnet 3.0.100-preview6-012264
IDE:VS2019
硬件
新建WEBAPI項目
API項目創建完成,下一步創建GRPC項目
添加控制台測試項目
為控制台項目添加nuget依賴:Google.Protobuf Grpc.Core Grpc.Tools
添加文件夾Protos 把GRPC項目的greet.proto復制到文件夾下面
右鍵單擊項目並選擇“編輯 GrpcGreeterClient.csproj”
<ItemGroup>
<Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
</ItemGroup>
生成控制台項目
在控制台程序中寫兩個測試方法
static async Task Main(string[] args)
{
Console.WriteLine("測試開始");
var a=await ApiTest();
var b=await GRpcTest();
Console.WriteLine($"WEBAPI耗時:{a}毫秒");
Console.WriteLine($"GRPC耗時:{b}毫秒");
Console.WriteLine("測試完成");
Console.ReadKey();
}
static async Task<long> ApiTest()
{
Stopwatch s=new Stopwatch();
s.Start();
HttpClient client=new HttpClient();
for (int i = 0; i < 1000; i++)
{
Console.WriteLine(await client.GetStringAsync("https://localhost:5001/api/values"));
}
return s.ElapsedMilliseconds;
}
static async Task<long> GRpcTest()
{
Stopwatch s = new Stopwatch();
s.Start();
var channel = new Channel("localhost:50051",
ChannelCredentials.Insecure);
var client = new Greeter.GreeterClient(channel);
for (int i = 0; i < 1000; i++)
{
var reply = await client.SayHelloAsync(
new HelloRequest { Name = "GreeterClient" });
Console.WriteLine("Greeting: " + reply.Message);
}
return s.ElapsedMilliseconds;
}
運行程序開始測試
WEBAPI耗時:48701毫秒
GRPC耗時:5485毫秒