大佬教程收集整理的这篇文章主要介绍了重新整理 .net core 实践篇—————grpc[三十三],大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
简单整理一下grpc。
什么是grpc?
这种模式一般来说就是代理模式,然后都是框架自我生成的。
grpc的特点:
提供几乎所有主流语言的实现,打破语言隔阂。
基于http/2,开放协议,收到广泛的支持,易于实现和集成
http/2 有个特点哈,就是更快,可以了解下,后续会专门整理关于http相关的,要等网络原理整理完后。
默认使用protocol buffers 序列化,性能相较于restful json好很多
工具链成熟,代码生成便捷,开箱即用
支持双向流式的请求和相应,对批量处理、低延迟场景友好
.net 生态对gRPC的支持情况:
提供基于httpClient 的原生框架的实现
提供了原生的ASP .net Core 集成库
提供完整的代码工具
visual @R_197_11561@dio 和 visual @R_197_11561@ido Code 提供proto 文件的智能提示 实践:
service 服务端:
.net core 在服务端使用的包:
客户端使用的包:
google.protobuf
Grpc.Net.Client
Grpc.Net.ClientFactory
Grpc.Tools
通过工具会生成proto 文件。
proto 文件:
gRPC 异常处理:
使用Grpc.Core.RpcException
使用Grpc.Core.Interceptors.Interceptor
grpc 的加密方式:
也可以不使用证书,里面可以设置,如果设置了,那么就是不加密的。
services.AddGrpcClient<Greeter.GreeterClient>(options =>
{
options.Address = new Uri("https://localhost:5001");
});
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
Greeter.GreeterClient service = context.requestservices.Getservice<Greeter.GreeterClient>();
Hellorequest Hellorequest = new Hellorequest();
var reply = await service.SayHelloAsync(Hellorequest);
Console.Read();
});
endpoints.MapControllers();
});
这样就可以调用了。
这里如果我们使用http://localhost:5000,那么访问会失败,显示协议不可用,不支持http1.1。
在服务端的配置文件中,这样写:
"Kestrel": {
"Endpoints": {
"http": {
"Url": "http://*:5000"
},
"https": {
"Url": "https://*:5001"
},
"http2": {
"Url": "http://*:5002",
"Protocols": "http2"
}
}
}
然后你就发现报错了:
这个问题也是比较简单的,因为http2默认使用加密,也就是应用解密的方式去解,自然就出错了。
那么需要这样:
AppContext.SetSwitch("System.Net.http.SocketshttpHandler.http2UnencryptedSupport",truE);
支持不使用加密方式的http2。如果是在内网内,可以不使用加密方式,这样更加流畅。
那么还有一种情况就是如果在有证书的情况下,那么我们的开发环境可能就跑不过了,因为本地使用自签名证书,通过不了验证。
下面是生成证书的powersHell脚本,百度的。
# setup certificate properties including the commonName (DNSName) property for Chrome 58+
$certificate = New-SelfSignedCertificate `
-Subject 改成自己想要的标题不要带乱七八糟的符号(安装证书的时候会显示这个) `
-DnsName 友好域名 `
-KeyAlgorithm RSA `
-KeyLength 2048 `
-NotBefore (Get-DatE) `
-NotAfter (Get-DatE).AddYears(2) `
-CertStoreLOCATIOn "cert:CurrentUserMy" `
-FriendlyName "证书的友好名称,在IIS指定的时候显示Certificate for .NET Core" `
-HashAlgorithm SHA256 `
-KeyUsage DigitalSignature, KeyEncipherment, DataEncipherment `
-TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.1")
$certificatePath = 'Cert:CurrentUserMy' + ($certificate.ThumbPrint)
# create temporary certificate path
$tmpPath = "C:tmp"
If(!(test-path $tmpPath))
{
New-Item -ItemType Directory -Force -Path $tmpPath
}
# set certificate password here
$pfxpassword = ConvertTo-SecureString -String "证书的密码" -Force -AsPlaintext
$pfxFilePath = "c:tmp证书的名称.pfx"
$cerFilePath = "c:tmp证书的名称.cer"
# create pfx certificate
Export-PfxCertificate -Cert $certificatePath -FilePath $pfxFilePath -password $pfxpassword
Export-Certificate -Cert $certificatePath -FilePath $cerFilePath
# import the pfx certificate
Import-PfxCertificate -FilePath $pfxFilePath Cert:LocalMachineMy -password $pfxpassword -Exportable
# trust the certificate by imporTing the pfx certificatE into your trusted root
Import-Certificate -FilePath $cerFilePath -CertStoreLOCATIOn Cert:CurrentUserRoot
# optionally delete the physical certificates (don’t delete the pfx file as you need to copy this to your app directory)
# Remove-Item $pfxFilePath
Remove-Item $cerFilePath
然后在服务端配置一下证书:
"Kestrel": {
"Endpoints": {
"http": {
"Url": "http://*:5000"
},
"https": {
"Url": "https://*:5001"
},
"http2": {
"Url": "http://*:5002",
"Protocols": "http2"
}
},
"Certificates": {
"Default": {
"Path": "self.cer",
"password": "123456"
}
}
}
Certificates 配置了默认证书。
那么客户端请求一下https://localhost:5001.
返回:
那么这个时候无论证书验证是否成功,都返回true:
services.AddGrpcClient<Greeter.GreeterClient>(options =>
{
options.Address = new Uri("https://localhost:5001");
}).ConfigurePriMaryhttpmessageHandler(provider =>
{
var handle = new SocketshttpHandler();
handle.SslOptions.RemoteCertificateValidationCallBACk = (a, b, c, d) => true;
return handle;
});
然后就可以访问了。
下面整理一下异常拦截器,如果我们服务端发生异常,我们希望有某种规律的错误发出。
测试异常:
public override Task<HelloReply> SayHello(Hellorequest request, ServerCallContext context)
{
throw new Exception("异常信息");
return Task.FromResult(new HelloReply
{
message = "Hello " + request.Name
});
}
@H_489_234@
通过异常拦截器过滤一下:
services.AddGrpc(options =>
{
options.EnableDetailedErrors = false;
options.Interceptors.Add<ExceptionInterceptor>();
});
具体异常拦截类:
public override async Task<TResponse> UnaryServerHandler<Trequest, TResponse>(Trequest request, ServerCallContext context, UnaryServerMethod<Trequest, TResponse> conTinuation)
{
try
{
return await base.UnaryServerHandler(request, context, conTinuation);
}
catch (Exception eX)
{
//log 处理
Metadata entries = new Metadata();
entries.Add("message",ex.messagE);
throw new RpcException(new Status(StatusCode.Unknown, "Unknown"), entries);
}
}
调试:
下一节实践一下用工具生成grpc 代码。
以上是大佬教程为你收集整理的重新整理 .net core 实践篇—————grpc[三十三]全部内容,希望文章能够帮你解决重新整理 .net core 实践篇—————grpc[三十三]所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。