.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的模板可以快速生成Grpc Server的模板代码,当然,我这里还是手动去创建项目。
⒈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 = ,Username = "fanqi",Password = "admin",Phone="",Email="fanqi@coreqi.cn"
},
new User
{
Id = ,Username = "gaoxing",Password="admin",Phone="",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 = });
await channel.ShutdownAsync();
return Json(new { User = user });
}
.Net Core 3.0使用Grpc进行远程过程调用的更多相关文章
- ASP.NET Core 3.0 使用gRPC
一.简介 gRPC 是一个由Google开源的,跨语言的,高性能的远程过程调用(RPC)框架. gRPC使客户端和服务端应用程序可以透明地进行通信,并简化了连接系统的构建.它使用HTTP/2作为通信协 ...
- Thrift架构~从图中理解thrift,它事实上是一种远程过程调用
thrift为我们简化了tcp通讯,它可以使用我们方便的建立各种语言的服务端与客户端,并实现客户端对服务器的远程过程调用,简单的说就是服务器通过thrift架构对外开放一些接口,并自己实现这些接口,如 ...
- RabbitMQ入门教程(八):远程过程调用RPC
原文:RabbitMQ入门教程(八):远程过程调用RPC 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.cs ...
- .net core 1.0 Web MVC 自定义认证过程
通过官方的介绍可知,若要本地开始部署搭建一个基于.net core 1.0的Web应用,需要下载dotnet SDK,或在Visual Studio IDE之上安装相关插件以布置开发环境.为了使开发环 ...
- net core 3.0 之Grpc新特性小试牛刀
相信微服务大家伙都有听说和知道,好处弊端咱也不多说了,Grpc算是一个比较全面的微服务框架,也得到微软的支持 总结下来就是,跨平台,可靠,通信快,扩展性强,网络消耗小,模板多语言通用 光说好处,没 ...
- ASP.NET Core 3.0 使用 gRPC无法编译问题
一.问题 创建了gRPC项目后,编译发现报错: 二.解决 1.检查项目路径是否存在中文 2.检查当前Windows用户目录是否为非英文字符,如果是则必须改为英文 修改方法: https://jingy ...
- rabbitMQ学习3-RPC远程过程调用
将一个函数运行在远程计算机上并且等待获取那里的结果,这个称作远程过程调用(Remote Procedure Call)或者 RPC. RPC是一个计算机通信协议. 比喻 将计算机服务运行理解为厨师做饭 ...
- RabbitMQ九:远程过程调用RPC
定义 RPC(Remote Procedure Call Protocol)——远程过程调用协议:它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议.RPC协议假定某些传输协议 ...
- RPC之远程过程调用
一. 简介 将一个函数运行在远程计算机上并且等待获取那里的结果,这个称作远程过程调用(Remote Procedure Call)或者 RPC. RPC是一个计算机通信协议. 1. 类比: 将计算机服 ...
随机推荐
- noi.ac #535 生成树
题目链接:戳我 我们考虑按照编号依次加点,然后维护一个栈. 预设生成树的颜色为color. 对于当前点x,如果它和栈首的点连边颜色相同,那么他们的连边可以作为生成树上面的边,点i已经连接,直接brea ...
- Luogu P5564 [Celeste-B]Say Goodbye (多项式、FFT、Burnside引理、组合计数)
题目链接 https://www.luogu.org/problem/P5564 题解 这题最重要的一步是读明白题. 为了方便起见下面设环长可以是\(1\), 最后统计答案时去掉即可. 实际上就相当于 ...
- BZOJ 5330 Luogu P4607 [SDOI2018]反回文串 (莫比乌斯反演、Pollard Rho算法)
题目链接 (BZOJ) https://www.lydsy.com/JudgeOnline/problem.php?id=5330 (Luogu) https://www.luogu.org/prob ...
- Android_(控件)使用自定义控件在屏幕中绘制一条虚线
在Android屏幕中绘制虚线,最通用的是自定义控件DashedLine,再将自定义控件放入xml布局中 运行截图: 程序结构 package com.example.asus.gary_042; i ...
- SpringMVC接收请求参数和页面传参
接收请求参数: 1,使用HttpServletRequest获取 @RequestMapping("/login.do") public String login(HttpServ ...
- 撩测试MM神器cypress使用入门
不很久不很久以前 据说某家公司有两位前端,天天撸bug,为啥嘞?只怪测试MM倾人国,轻语哥哥有bug.✧(๑•̀ㅂ•́)و✧ 可是最近两位有点犯愁 Σ(っ °Д °;)っ.测试MM有几次提了紧急bug ...
- Java-JDK-windows和linux版-百度云下载
链接: https://pan.baidu.com/s/15vjk4PNzuItd5vHJ6deq3Q 关注以下公众号,回复[9757],获取提取码 linux:jdk-8u221-linux-x64 ...
- 没有安装zip引发的一系列安装
安装一个php框架的时候提示不能在线解压缩 通过phpinfo查看没有加载zip扩展,安装开始. 先安装了一次发现不能make,,,什么情况!!! 提示这个错误,好吧解决.make: *** No t ...
- LC 609. Find Duplicate File in System
Given a list of directory info including directory path, and all the files with contents in this dir ...
- SVN图标详解
蓝色的加号 : 把这个文件已经添加到版本控制软件内 绿色的对勾 : 客户端和服务器端的代码一致 红色的叹号 : 客户端和服务器端两边的代码不一致 黄色的叹号 : 文件冲突 蓝色的问号 : 这个文件不在 ...