.net core 微服务 集成Ocelot 和Nacos 之后使用grpc 如何实现服务与服务之间的调用

发布时间 2023-06-12 16:57:16作者: .net小峰

在 .NET Core 微服务中使用 gRPC 调用其他服务,你需要完成以下步骤:

1. 定义服务契约: 你需要定义你的服务、方法以及消息类型,以便客户端和服务端协商通信。

2. 生成代码: 你需要使用 gRPC 工具生成客户端和服务端的代码,这样你就可以在应用程序中使用它们。

3. 实现服务: 你需要实现服务契约中指定的方法。

4. 注册服务: 将服务注册到你的服务注册中心中,所以其他服务可以发现并访问你的服务。

5. 调用服务: 你需要使用生成的客户端代码从其他服务中调用服务。

具体步骤如下:

1. 定义服务契约,你可以使用 protobuf 语法来定义它。并在服务端和客户端中共享服务契约文件。

syntax = "proto3";

package MyService;

service MyService{
rpc DoSomething (MyRequest) returns (MyResponse) {}
}

message MyRequest {
string name = 1;
}

message MyResponse {
string message = 1;
}

  

2. 生成代码,可以使用以下命令生成代码:

# 生成服务端代码
protoc --csharp_out=. --grpc_out=. --plugin=protoc-gen-grpc=/usr/local/bin/grpc_csharp_plugin MyService.proto

# 生成客户端代码
protoc --csharp_out=. --grpc_out=. --plugin=protoc-gen-grpc=/usr/local/bin/grpc_csharp_plugin MyService.proto

3. 实现服务,你需要实现服务契约中指定的方法。

public class MyService : MyServiceBase
{
public override Task<MyResponse> DoSomething(MyRequest request,
ServerCallContext context)
{
return Task.FromResult(new MyResponse()
{
Message = $"Hello, {request.Name}"
});
}
}

 

  

4. 在服务完成后,你需要将其注册到服务注册中心。比如,在使用 Nacos 作为注册中心的情况下,你可以在 Startup.cs 中进行注册。

public void ConfigureServices(IServiceCollection services)
{
// 添加 gRPC 服务
services.AddGrpc();

// 配置服务发现
services.AddNacosDiscovery(Configuration.GetSection("NacosDiscovery"));
}

 

5. 调用服务,你需要使用生成的客户端代码从其他服务中调用服务。

var channel = new Channel("my-service:50051", ChannelCredentials.Insecure);
var client = new MyService.MyServiceClient(channel);

var reply = await client.DoSomethingAsync(new MyRequest { Name = "Bob" });

Console.WriteLine(reply.Message);

 

其中,`my-service` 是要调用的服务的名称,它已经在 Nacos 注册中心中注册过了。

需要注意,如果你在 .NET Core 中使用 Ocelot 和 Nacos 作为你的网关和服务注册中心,你需要在 Ocelot 中添加以下配置,以便 Ocelot 可以将请求路由到正确的端点:

{
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "my-service",
"Port": 50051
}
],
"UpstreamPathTemplate": "/my-service/{*catch-all}"
}

 

在这里,`DownstreamHostAndPorts` 包含要调用的 g

"GlobalConfiguration": {
"GrpcChannelOptions": {
"MaxReceiveMessageSize": "67108864",
"MaxSendMessageSize": "67108864",
"KeepAliveTime": "00:00:30",
"EnableCompression": true
}
}

 

RPC 服务的主机和端口号,`UpstreamPathTemplate` 包含 Ocelot 网关的路由映射,它应该匹配你的 gRPC 服务路径和参数。

 

Ocelot 是一个 .NET Core 的 API 网关,它能够处理传入请求并将它们路由到 API 的正确端点。我们可以使用 Ocelot 作为前端网关,接收客户端的请求,然后将它们路由到我们的 gRPC 服务上。

首先,我们需要在 Ocelot 中启用 gRPC 协议。我们可以通过以下方式在 Ocelot 中添加 gRPC 协议的支持:

1. 安装 Ocelot.GrpcHttpGateway 中间件包
2. 在 Ocelot 配置文件中添加以下代码:

 

在上面的配置中,我们可以设置 gRPC 的一些选项,例如最大接收/发送消息大小、保持连接时间和启用压缩。

接下来,在 Ocelot 的路由中,我们需要将 gRPC 请求的端点指向我们的 gRPC 服务:

{
"DownstreamPathTemplate": "/{service}/{method}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5000
}
],
"UpstreamPathTemplate": "/{service}/{method}",
"UpstreamHttpMethod": [ "POST" ],
"RouteClaimsRequirement": null,
"AuthenticationOptions": null,
"RequestIdKey": null,
"FileCacheOptions": null,
"QoSOptions": null,
"LoadBalancerOptions": null,
"DownstreamHeaderTransform": null,
"UpstreamHeaderTransform": null,
"DownstreamHostHeader": null,
"Key": "grpc_service",
"DelegatingHandlers": [],
"DangerousAcceptAnyServerCertificateValidator": null,
"HttpHandlerOptions": null,
"RateLimitOptions": null,
"UseServiceDiscovery": false,
"ServiceName": null
}

 

在上面的路由配置中,我们可以看到:

- DownstreamHostAndPorts 中指定了我们的 gRPC 服务的主机和端口;
- UpstreamPathTemplate 和 DownstreamPathTemplate 指定了请求的路径。其中,UpstreamPathTemplate 描述了网关将接收的路由,而 DownstreamPathTemplate 描述了该路由将被路由到的服务路径;
- Key 属性定义了服务的唯一标识符,用于 Ocelot 中的缓存和负载平衡;
- UpstreamHttpMethod 属性设置为 POST,因为 gRPC 使用 HTTP/2 而不是 HTTP/1.1。

最后,我们需要将 Ocelot 集成到 Nacos 中,以便我们可以动态地将请求路由到正确的端点。这可以通过在 Ocelot 配置文件中添加以下代码来实现:

"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8848,
"Type": "Polling",
"PollingInterval": "10",
"Namespace": "",
"ConfigurationKey": "",
"Token": "",
"EnableChildrenMonitor": false

 

在上面的配置中,我们可以指定 Nacos 的主机和端口,以及轮询服务的间隔时间。我们还可以设置其他选项,例如命名空间和令牌。

通过上述步骤,我们就成功地将 gRPC 和 Ocelot 集成起来,实现了微服务之间的调用和请求转发。