Location>code7788 >text

NET Microservices Framework

Popularity:377 ℃/2024-08-28 10:49:37

preamble

Microservices architecture has become one of the key technologies to build efficient and scalable systems, however, many existing microservices frameworks are often too complex , making it difficult for ordinary developers to quickly get started and experience the convenience of microservices. In order to solve this problem, the authors have crafted one of the most grounded .NET microservices framework to help us easily build and manage microservices applications.

This framework not only supports Consul service registration and discovery, but also comes with a series of advanced features, including configuration center, link tracking (APM), service gateway, etc., which greatly simplifies the process of microservice development and operation and maintenance.

In addition, the framework also implements Saga distributed transactions, RabbitMQ event bus and other features to ensure that the system can efficiently handle complex business logic. What's more, it provides a user-friendly Dashboard management panel, which makes it easy to monitor and manage microservice clusters.

Through the introduction of this article you can learn how to quickly get started and take full advantage of these features to build both efficient and stable microservices applications.

Projects

Wing is committed to building a powerful and easy-to-use .NET microservices framework that supports the .NET 6+ operating platform.

The framework has the following features:

1. Service registration and discovery: Supports Consul service registration and discovery mechanisms to ensure automatic discovery and dynamic management between services.

2. Inter-service communication: It supports both HTTP and gRPC invocation methods and has a built-in load balancer for efficient inter-service communication.

3、Service strategy and exception handling: Provide service policy configuration and support service abnormality degradation processing to ensure system stability and reliability.

4. Saga distributed transactions: Supports three recovery strategies (forward recovery, backward recovery, and previous and then backward) to ensure the consistency and integrity of transactions.

5. Configuration Center: Built-in configuration center to realize online centralized and unified management of service configuration.

6、Link tracing and performance monitoring: Supports HTTP/gRPC/SQL link tracing (APM) and time-consumption analysis statistics to help developers quickly locate performance bottlenecks.

7. Service gateway: Built-in service gateway that supports global service policy and personalized service policy configuration, simplifying service portal management.

8、Event bus: Supports the RabbitMQ event bus for asynchronous communication and event delivery between services.

9. Management interface: Provides a user-friendly Dashboard management interface that makes it easy to monitor and manage the entire microservice cluster.

The Wing framework provides developers with a powerful and intuitive development platform to help quickly build and manage efficient and scalable microservices applications.

Quick Start

1. Service registration

What is service registration?

Service registration is the process of registering the service's IP, port, and other information when the service is started to theConsul

Create a Web API project

Preparing ahead: installing and launching Consul

Open Visual Studio 2022 and create a Web API project.

Installation of dependency packages

dotnet add package 

Program Code

();

Add Configuration

{
  // Whether to enable the configuration center, enabled by default
  "ConfigCenterEnabled": false,
  "Consul": {
    "Url": "http://localhost:8500",
    "Service": {
      //Http  Grpc
      "Option": "Http",
      "HealthCheck": {
        "Url": "http://localhost:1210/health",
        //Unit: second
        "Timeout": 10,
        //Unit: second
        "Interval": 10
      },
      "Name": "Wing.Demo_1.2.1",
      "Host": "localhost",
      "Port": 1210,
      "Tag": "",
      "LoadBalancer": {
        //RoundRobin  WeightRoundRobin LeastConnection
        "Option": "WeightRoundRobin",
        //weights
        "Weight": 60
      },
      "Scheme": "http",
      "Developer": "linguicheng"
    },
    //Timed synchronization data interval in seconds Less than or equal to 0 means immediate response
    "Interval": 10,
    //data center
    "DataCenter": "dc1",
    //Waiting time, in minutes
    "WaitTime": 3
  }
}

See how it works

After the program runs, open the consul UI management interface and you can see the registration serviceWing.Demo_1.2The details are shown in the figure below:

2、Start UI

beWingA visual operation management system in the microservices framework, the main functions are service governance, configuration center, APM management, Saga distributed transaction query.

Installation of dependency packages

Install service registration nuget packageUI visualization interface to manage nuget packages, select the corresponding database driver (Refer to the FreeSql website), using SqlServer as an example, to install the

dotnet add package 
dotnet add package 

Program Code

using Wing;
var builder = (args);
(builder => ());
().AddWingUI();

See how it works

After the program is run, the browser visits , the running effect is shown below:

You can see the example1.2 Injected services `Wing.Demo_1.2'

3. Service discovery and invocation

What is service discovery?

Service discovery means that service registration information is refreshed locally at regular intervals after the service is started or obtained in real time.Consulof service information.

Installation of dependency packages

dotnet add package 

Grpc Health Screening

protobuf file

syntax = "proto3";
package .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 Codes

public class HealthCheck : 
{
    public override Task<HealthCheckResponse> Check(HealthCheckRequest request, ServerCallContext context)
    {
        return (new HealthCheckResponse() { Status =  });
    }
​
    public override async Task Watch(HealthCheckRequest request, IServerStreamWriter<HealthCheckResponse> responseStream, ServerCallContext context)
    {
        await (new HealthCheckResponse()
        { Status =  });
    }
}

Program Code

using Wing;
var builder = (args);
(builder => ());
// Add services to the container.
();
();
​
var app = ();
// Configure the HTTP request pipeline.
<GreeterService>();
("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: /fwlink/?linkid=2086909");
();

operational effect

Run the current program and start the example1.3If you visit your browser, you can see the injected Grpc service.Wing.Demo_1.4The result is shown in the figure below:

in the sample1.2 Calls the current Grpc service in theSayHellomethod with the following code:

[HttpGet("hello")]
public Task<string> SayHello()
{
    return _serviceFactory.InvokeAsync("Wing.Demo_1.4", async serviceAddr =>
    {
        var channel = (());
        var greeterClient = new (channel);
        var result = await (new HelloRequest { Name = "Wing" });
        return ;
    });
}

running example1.2Browser accesshttp://localhost:1210/weatherforecast/hello The result is shown in the figure below:

4. Start the service gateway

The service gateway is the only entrance of the system to the outside world, which encapsulates the internal architecture of the system and provides customized APIs for each client. All clients and consumers access the microservices through a unified gateway, and all non-business functions are handled at the gateway layer.

Installation of dependency packages

Install service registration nuget packageService Gateway nuget package, select the corresponding database driver (Refer to the FreeSql website open in new window), using SqlServer as an example, to install the, the request log supports local message queues and distributed message queues for asynchronous persistence, basically does not affect the performance of the gateway. If you do not want to record the request log , you can not install the package .

If you want to enable theEventBusTo log requests, you need to install the RabbitMQ nuget package.

dotnet add package 
dotnet add package 
dotnet add package 
dotnet add package 

Program Code

using Wing;
​
var builder = (args);
​
(builder => ());
​
// Add services to the container.
​
();
​
()
            .AddPersistence()
            .AddGateWay()
            .AddEventBus();// If you don't want to use EventBus to log requests, you can remove this line of code
var app = ();
​
// Configure the HTTP request pipeline.
​
();
​
();
​
();
​
();

Add Configuration

{
  // Whether to enable the configuration center, enabled by default
  "ConfigCenterEnabled": false,
  "Consul": {
    "Url": "http://localhost:8500",
    "Service": {
      //Http  Grpc
      "Option": "Http",
      "HealthCheck": {
        "Url": "http://localhost:1510/health",
        //Unit: second
        "Timeout": 10,
        //Unit: second
        "Interval": 10
      },
      "Name": "Wing.Demo_1.5",
      "Host": "localhost",
      "Port": 1510,
      "LoadBalancer": {
        //RoundRobin  WeightRoundRobin LeastConnection
        "Option": "WeightRoundRobin",
        //weights
        "Weight": 50
      },
      "Scheme": "http",
      "Developer": "linguicheng"
    },
    //Timed synchronization data interval in seconds Less than or equal to 0 means immediate response
    "Interval": 10,
    //data center
    "DataCenter": "dc1",
    //Waiting time, in minutes
    "WaitTime": 3
  },
  "ConnectionStrings": {
    "Wing": "Data Source=192.168.56.96;User Id=sa;Password=wing123.;Initial Catalog=Wing;TrustServerCertificate=true;Pooling=true;Min Pool Size=1"
  },
  //Automatic synchronization of entity structures to the database
  "UseAutoSyncStructure": true,
  // If EventBus is not enabled, you can remove the RabbitMQ configuration
  "RabbitMQ": {
    "HostName": "192.168.56.99",
    "UserName": "admin",
    "Password": "admin",
    "VirtualHost": "/",
    "Port": 5672,
    //Message expiration time, in milliseconds, the expiration time will be automatically routed to the dead message queue, less than or equal to 0 is permanently effective
    "MessageTTL": 0,
    "ExchangeName": "",
    //Number of messages per delivery
    "PrefetchCount": 1
  },
  "Gateway": {
    // Request log
    "Log": {
      // Whether to enable gateway logging
      "IsEnabled": true,
      // Whether to enable the event bus (RabbitMQ) to store logs, recommended for production environments, can improve program performance
      "UseEventBus": false
    }
  }
}

See how it works

running example1.2 And start the current example program, browser access, run the following figure:

running example1.3If you access it with a browser, you can see the gateway request logs, which run as shown below:

service address composition

The request service address defaults to {gateway IP or domain name}/{service name}/{service route}, for example:http://localhost:1510/Wing.Demo_1.2/weatherforecast

Attention:More details can be found in the official Wing documentation, as follows

Project Address

Github:/Wing

Gitee:/linguicheng/Wing

Document Address:/Wing

Example Address:/linguicheng/wing-demo

Open source protocols:Based on the MIT protocol permanent open source free to use

ultimate

If you found this article helpful, why not support it with a like? Your support is what keeps me motivated to continue sharing my knowledge. Feel free to leave a comment if you have any questions or need further help.

You can also join WeChat[DotNet Technician] community to share ideas and grow with other tech-loving peers!