.Net Core 3.0使用Grpc进行远程过程调用

因为.Net Core3.0已经把Grpc作为一等臣民了,作为爱好新技术的我,当然要尝鲜体验一下了,当然感觉是Grpc作为跨语言的产品做的相当好喽,比起Dubbo这种的,优势和劣势还是比较明显的。

  我这里的环境是VS2019以及,Net Core3.0预览5版,.Net Core3.0预览SDK没有随着VS2019一同安装,如果大家想要体验的话,需要先安装.Net Core3.0的SDK,并在VS2019设置中开启.Net Core的预览才可以使用。

.Net Core 3.0使用Grpc进行远程过程调用

* .Net Core 3.0提供了Grpc的模板可以快速生成Grpc Server的模板代码,当然,我这里还是手动去创建项目。

.Net Core 3.0使用Grpc进行远程过程调用

⒈Server端

  1.创建一个ASP.NET Core Web应用程序

  2.引入依赖

Install-Package Grpc.AspNetCore.Server -pre
Install-Package Google.Protobuf
Install-Package Grpc.Tools

3.编写Proto文件

syntax = "proto3";

package Service;

service UserService{
	rpc GetUserById (UserId) returns (User) {}
}

message UserId{
	int32 id = 1;
}
message User{
	int32 id = 1;
	string username = 2;
	string password = 3;
	string phone = 4;
	string email = 5;
}

4.编辑当前项目的csproj文件,配置Proto的生成策略

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Protobuf Include="Protos/*.proto" GrpcServices="Server" OutputDir="%(RelativeDir)" CompileOutputs="false" />
  </ItemGroup>

  <ItemGroup>
    <None Remove="Protos\user.proto" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Google.Protobuf" Version="3.7.0" />
    <PackageReference Include="Grpc.AspNetCore.Server" Version="0.1.20-pre1" />
    <PackageReference Include="Grpc.Tools" Version="1.20.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0-preview5-19227-01" />
  </ItemGroup>

  <ItemGroup>
    <Protobuf Update="Protos\user.proto">
      <OutputDir>%(RelativeDir)</OutputDir>
    </Protobuf>
  </ItemGroup>

</Project>

 5.编写服务的实现

using Grpc.Core;
using Microsoft.Extensions.Logging;
using Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GrpcGreeter.Services
{
    public class UserServiceImpl:UserService.UserServiceBase
    {
        public ILogger<UserServiceImpl> _logger;
        public UserServiceImpl(ILogger<UserServiceImpl> logger)
        {
            this._logger = logger;
        }
        public static IList<User> users = new List<User>
        {
            new User
            { Id = 1,Username = "fanqi",Password = "admin",Phone="13800138000",Email="fanqi@coreqi.cn"
            },
            new User
            {
                Id = 2,Username = "gaoxing",Password="admin",Phone="138001380000",Email = "gaoxing@coreqi.cn"
            }
        };
        public override Task<User> GetUserById(UserId request, ServerCallContext context)
        {
            var httpContext = context.GetHttpContext(); //我没有用到httpContext
            _logger.LogInformation("成功调用");
            User user = users.FirstOrDefault(f => f.Id == request.Id);
            return Task.FromResult(user);
        }
    }
}

⒍在Startup中配置Grpc

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GrpcGreeter.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace GrpcGreeterServer
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddGrpc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService<UserServiceImpl>();
            });
        }
    }
}

 7.在launchSettings.json中配置Grpc

{
  "profiles": {
    "GrpcGreeter": {
      "commandName": "Project",
      "launchBrowser": false,
      "applicationUrl": "http://localhost:50051",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

8.在appsettings.json中配置Grpc

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Kestrel": {
    "EndpointDefaults": {
      "Protocols": "Http2"
    }
  }
}

⒉Client端

  1.创建一个ASP.NET Core Web应用程序

  2.引入依赖

Install-Package Grpc.Core
Install-Package Google.Protobuf
Install-Package Grpc.Tools

 3.将Server的Proto文件复制到Client项目中来

  4.编辑当前项目的csproj文件,配置Proto的生成策略

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <None Remove="Protos\greet.proto" />
    <None Remove="Protos\user.proto" />
  </ItemGroup>

  <ItemGroup>
    <Protobuf Include="Protos\greet.proto" GrpcServices="Client">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      <OutputDir>%(RelativeDir)</OutputDir>
      <CompileOutputs>false</CompileOutputs>
      <Generator>MSBuild:Compile</Generator>
    </Protobuf>
    <Protobuf Include="Protos\user.proto" GrpcServices="Client">
      <OutputDir>%(RelativeDir)</OutputDir>
      <CompileOutputs>false</CompileOutputs>
    </Protobuf>
  </ItemGroup>
  

  <ItemGroup>
    <PackageReference Include="Google.Protobuf" Version="3.7.0" />
    <PackageReference Include="Grpc.Core" Version="1.20.1" />
    <PackageReference Include="Grpc.Tools" Version="1.20.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0-preview5-19227-01" />
  </ItemGroup>

</Project>

5.在代码中使用Grpc

public async Task<IActionResult> Index()
        {
            var channel = new Channel("localhost:50051", ChannelCredentials.Insecure);
            var client = new UserService.UserServiceClient(channel);
            var user = await client.GetUserByIdAsync(new UserId { Id = 1});
            await channel.ShutdownAsync();
            return Json(new { User = user });
        }

作者:出处:https://www.cnblogs.com/fanqisoft/

本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。

原文出处:博客园【作者:SpringCore】

原文链接:https://www.cnblogs.com/fanqisoft/p/10857848.html

本文观点不代表Dotnet9立场,转载请联系原作者。

发表评论

登录后才能评论