Talk about how Yarp combined with Nacos to complete service discovery

background

Yarp After this reverse agent comes out, I believe many people are still paying attention to it.

In Yarp, the configuration of reverse proxy is also based on the configuration file by default, and many bosses have made this configuration into a database configuration + visual interface.

After careful consideration, it seems that the database configuration is only convenient for configuration management, and the service registration and discovery are still weak.

For example, the order service adds three instances. At this time, you need to configure and add these three instances.

If you add more services and the frequency is high, you certainly don't want to intervene manually. It will be troublesome.

Especially when a registry is introduced, you want it to automatically adapt to these changes.

Based on this situation, Lao Huang took the time to try to combine Yarp and Nacos to adapt the addition and reduction of services and instances, which can be dynamic and reduce human intervention to a certain extent.

Let's take a brief look.

Sample services

Prepare the following services

  • YarpWithNacosSample reverse proxy integration
  • OrderSvcA order Service-A
  • OrderSvcB order service - B
  • UserSvc user service

Two order services are used to simulate the online and offline of service instances, and user services are used to simulate the online and offline of services.

The codes of the following three business services are basically the same

Only the of user services are posted.

using Nacos.AspNetCore.V2;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddNacosAspNet(builder.Configuration);

builder.Services.AddControllers();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/", () =>
    {
        return Results.Ok("user svc 9001");
    });
});

app.Run("http://*:9001");

Then configuration

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Nacos.AspNetCore": "Information",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "nacos": {
    "ServerAddresses": [ "http://localhost:8848" ],
    "DefaultTimeOut": 15000,
    "Namespace": "yarp",
    "ListenInterval": 1000,
    "ServiceName": "usersvc",
    "GroupName": "DEFAULT_GROUP",
    "ClusterName": "DEFAULT",
    "Weight": 100,
    "RegisterEnabled": true,
    "InstanceEnabled": true,
    "Ephemeral": true,
    "Secure": false,
    "ConfigUseRpc": true,
    "NamingUseRpc": true
  }
}

Let's take a look at the key reverse proxy.

using global::Nacos.V2.DependencyInjection;
using Yarp.ReverseProxy.Configuration;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddNacosV2Naming(x =>
{
    x.ServerAddresses = new List<string> { "http://localhost:8848/" };
    x.Namespace = "yarp";

    x.NamingUseRpc = true;
});

builder.Services.AddReverseProxy()
    .AddNacosServiceDiscovery(
    groupNames: "DEFAULT_GROUP", 
    percount:100,
    enableAutoRefreshService: true,
    autoRefreshPeriod: 30);

var app = builder.Build();

app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/yarp", (IProxyConfigProvider provider) =>
    {
        var res = provider.GetConfig();
        return Results.Ok(res);
    });
    endpoints.MapReverseProxy();
});

app.Run("http://*:9091");

You can see that the reverse proxy project is not registered with Nacos, because it only needs to discover other services and does not need to be discovered by other services.

Start OrderSvcA and register it with Nacos.

Then start the reverse proxy project. At this time, you can see the log and output the trace of adding OrderSvcA.

Then visit localhost:9091/yarp to see the current configuration.

Then access OrderSvc through the reverse proxy.

Next, start OrderSvcB and register it with Nacos.

At this time, the reverse proxy project will show that the new instance has been added.

At this time, there will be a load balancing policy to access ordersvc.

Finally, let's take a look at the launch of the new service and start UserSvc.

It's normal to visit again.

It should be noted here that the newly added services will not be updated to the configuration in real time, depending on the automatic refresh interval. At present, Nacos does not provide notification of service changes, but only service instances. Therefore, this part should be queried regularly and actively.

At this point, the demonstration is basically over.

However, some people should have questions about the forwarding rules. Why is it [reverse proxy address / service name / relative path of service]

This is the default implementation, because there are 100 different rules for 100 people, including those that want to put request headers, query parameters, etc., so this one is open and can be replaced freely.

Write at the end

Yarp is still an interesting project, which should be used by many people later.

At present, this expansion pack is still a preview version, and no official version has been released. It is mainly to enrich the content.

Address of Nacos SDK CSharp: https://github.com/nacos-group/nacos-sdk-csharp

Address of Nacos CSharp extensions: https://github.com/catcherwong/nacos-csharp-extensions

Address of the sample code for this article: https://github.com/catcherwong-archive/2021/tree/main/YarpWithNacosSample

Keywords: .NET Nacos

Added by johncal on Fri, 31 Dec 2021 12:12:43 +0200