悳鎭的博客

导航

统计

webapi和GRPC性能对比

平台: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毫秒

 

posted on 2019-06-17 23:26 悳鎭 阅读(...) 评论(...) 编辑 收藏