跳至主要內容

1.4 服务发现与调用

linguicheng...大约 2 分钟

什么是服务发现?

服务发现是指服务启动后将服务注册信息定时同步刷新到本地或实时获取Consul的服务信息。

创建一个Grpc Service项目

安装依赖包

dotnet add package Wing.Consul

Grpc健康检查

protobuf文件

syntax = "proto3";
package grpc.health.v1;

message HealthCheckRequest {
	string service = 1;
}

message HealthCheckResponse {
	enum ServingStatus {
		UNKNOWN = 0;
		SERVING = 1;
		NOT_SERVING = 2;
	}
	ServingStatus status = 1;
}

service Health {
	rpc Check(HealthCheckRequest) returns (HealthCheckResponse);

	rpc Watch(HealthCheckRequest) returns (stream HealthCheckResponse);
}

HealthCheck代码

public class HealthCheck : Health.HealthBase
{
    public override Task<HealthCheckResponse> Check(HealthCheckRequest request, ServerCallContext context)
    {
        return Task.FromResult(new HealthCheckResponse() { Status = HealthCheckResponse.Types.ServingStatus.Serving });
    }

    public override async Task Watch(HealthCheckRequest request, IServerStreamWriter<HealthCheckResponse> responseStream, ServerCallContext context)
    {
        await responseStream.WriteAsync(new HealthCheckResponse()
        { Status = HealthCheckResponse.Types.ServingStatus.Serving });
    }
}

Program代码

using Wing;

var builder = WebApplication.CreateBuilder(args);

builder.Host.AddWing(builder => builder.AddConsul());

// Add services to the container.

builder.Services.AddGrpc();

builder.Services.AddWing();

var app = builder.Build();

// Configure the HTTP request pipeline.
app.MapGrpcService<GreeterService>();
app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");

app.Run();

添加配置

{
  // 是否启用配置中心,默认启用
  "ConfigCenterEnabled": false,
  "Consul": {
    "Url": "http://localhost:8500",
    "Service": {
      //Http  Grpc
      "Option": "Grpc",
      "HealthCheck": {
        "Url": "localhost:1410",
        //单位:秒
        "Timeout": 10,
        //单位:秒
        "Interval": 10,
        "GRPCUseTLS": false
      },
      "Name": "Wing.Demo_1.4",
      "Host": "localhost",
      "Port": 1410,
      "Tag": "",
      "LoadBalancer": {
        //RoundRobin  WeightRoundRobin LeastConnection
        "Option": "WeightRoundRobin",
        //权重
        "Weight": 4
      },
      "Scheme": "http",
      "Developer": "linguicheng"
    },
    //定时同步数据时间间隔,单位:秒 小于等于0表示立即响应
    "Interval": 10,
    //数据中心
    "DataCenter": "dc1",
    //等待时间,单位:分钟
    "WaitTime": 3
  }
}

查看运行效果

  • 在示例 1.2 中调用当前Grpc服务中SayHello方法,代码如下:
[HttpGet("hello")]
public Task<string> SayHello()
{
    return _serviceFactory.InvokeAsync("Wing.Demo_1.4", async serviceAddr =>
    {
        var channel = GrpcChannel.ForAddress(serviceAddr.ToString());
        var greeterClient = new Greeter.GreeterClient(channel);
        var result = await greeterClient.SayHelloAsync(new HelloRequest { Name = "Wing" });
        return result.Message;
    });
}
上次编辑于:
贡献者: linguicheng