Constructing microservice application on. net platform through silky framework

catalogue

prerequisite

  1. (must) install. net5 or. net6 sdk.

  2. (required) you can use visual studio or rider as a development tool.

  3. (required) you must prepare an available zookeeper service as the service registry.

  4. (mandatory) select redis service as the distributed cache service.

Building microservice applications using Web hosts

Developers can provide it through the. net platform Web host To build silky microservice applications.

The silky microservice application built with webhost can not only serve as a service provider of the microservice application (the service can communicate internally through the SilkyRpc framework); It also provides http services. http requests the webapi generated by the application service method (service entry) and accesses the relevant services provided by the micro service application through the routing rules set by silky.

We can quickly build a Silky microservice application using Web host through the following steps.

  1. Add a console application or ASP.NET Core Empty application

  1. Install the Silky.Agent.Host package

Install the Silky.Agent.Host package through Nuget Package Manger:

Or install the package through the console command:

PM> Install-Package Silky.Agent.Host -Version 3.0.2
  1. Building a silky host in the Main method
namespace Silky.Sample
{
    using Microsoft.Extensions.Hosting;
    using System.Threading.Tasks;
    class Program
    {
        public static async Task Main(string[] args)
        {
            await CreateHostBuilder(args).Build().RunAsync();
        }

        private static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
                    .ConfigureSilkyWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
               
        }
    }
}
  1. Configure the service and configuration middleware and routing in the enabling class
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Silky.Http.Core;

namespace Silky.Sample
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            // Add necessary services
            services.AddSilkyHttpCore()
                .AddSwaggerDocuments()
                .AddRouting();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // Determine whether the development environment
            if (env.IsDevelopment())
            {
                // The development environment uses the developer exception mode page
                app.UseDeveloperExceptionPage();
                // The development environment uses Swagger online documentation
                app.UseSwaggerDocuments();
            }

            // Using routing Middleware
            app.UseRouting();
            
            // Add other asp.net core middleware

            // Configure routing
            app.UseEndpoints(endpoints => 
              { 
                // Configure SilkyRpc routing
                endpoints.MapSilkyRpcServices(); 
              });
        }
    }
}
  1. Update configuration

silky supports configuration in JSON or yml format. You can specify the configuration information for the public configuration item through appsettings.json, or update the configuration properties for the specified environment by adding a new appsettings.${ENVIRONMENT}.json file.

Generally, you must specify configuration items such as token of rpc communication and address of service registry. If you use redis as the cache service, you also need to set the distributedCache:redis:isEnabled configuration item to true and give the address of the redis service cache.

Add the following configuration attributes in appsettings.json configuration file:

{
  "RegistryCenter": {
    "Type": "Zookeeper",
    "ConnectionStrings": "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183;127.0.0.1:2184,127.0.0.1:2185,127.0.0.1:2186"
  },
  "DistributedCache": {
    "Redis": {
      "IsEnabled": true,
      "Configuration": "127.0.0.1:6379,defaultDatabase=0"
    }
  },
  "Rpc": {
    "Token": "ypjdYOzNd4FwENJiEARMLWwK0v7QUHPW",
    "Port": 2200
  }
}

Copy the properties of the configuration file to the output directory and set it to always copy or copy if it is newer.

  1. Create zookeeper service and redis cache service

In this example project, we use Zookeeper as the service registry. In the example project of silky, we give the details of various basic services Docker compose orchestration file , including zookeeper and redis services.

take docker-compose.zookeeper.yml and docker-compose.redis.yml Copy to the local, save the file with the same name, and enter the local directory where the file is saved.

# Create a file named silky_service_net
docker network create silky_service_net

# Using docker compose to create zookeeper and redis services
docker-compose -f docker-compose.zookeeper.yml -f docker-compose.redis.yml up -d
  1. Other layers of microservice applications (projects)

After completing the host project, you can add other projects such as application interface layer, application layer, domain layer and infrastructure layer. Please refer to Microservice architecture Node.

The division of a typical microservice module is basically consistent with the application division of the traditional DDD domain model. The application interface needs to be abstracted as an assembly to be referenced by other microservice applications. Other microservice applications generate RPC proxy through the application interface to communicate with the microservice.

The project structure of a typical microservice module is as follows:

The dependencies of the project are as follows:

(1) The host project depends on the application layer to achieve the hosting of applications.

(2) The application interface layer is used to define service interfaces and DTO objects. The application layer needs to rely on the application interface layer to implement the defined service interfaces.

(3) The domain layer is mainly used to implement specific business logic and can rely on its own application interface layer and the application interface layer of other microservice applications (developers can install application interface projects of other microservice applications through nuget package or directly add projects for reference); The reason why the domain layer relies on its own application interface layer is to facilitate the use of DTO objects; The application interface layer that references other microservices can communicate with other microservices through the SilkyRPC framework through the dynamic proxy generated by the interface.

(4) Domain. Shared is generally used to define value types and enumerations in the ddd concept, which can be easily referenced by other microservice applications.

(5) As the basic service layer, entityframework provides data access. Of course, developers can also choose to use other ORM frameworks.

  1. Definition and implementation of application interface

Application interface layer (Silky.Sample.Application.Contracts) installation package Silky.Rpc:

Or install the package through the console command:

PM> Install-Package Silky.Rpc -Version 3.0.2

Add a service interface IGreetingAppService and define a Say() method. The application interface needs to be identified with the [ServiceRoute] feature.

[ServiceRoute]
public interface IGreetingAppService
{
    Task<string> Say(string line);
}

Next, we need the application layer (Silky.Sample.Application) to rely on (Reference) the application interface layer (Silky.Sample.Application.Contracts), and add a service class greengapservice to implement the service interface IGreetingAppService.

    public class GreetingAppService : IGreetingAppService
    {
        public Task<string> Say(string line)
        {
            return Task.FromResult($"Hello {line}");
        }
    }
  1. Online debugging via Swagger documentation

Run the application to open the swagger online document. Developers can debug the API through the online documentation generated by swagger.

Using. NET general host to build microservice application

Developers can provide it through the. net platform General host To build silky microservice applications.

Using. NET general host to build microservice applications can only be used as service providers to communicate with other microservice applications through SilkyRPC framework; http service cannot be provided, that is, the micro service application cannot be accessed directly outside the cluster, and the services of the micro service application can only be accessed through the gateway or other micro service applications providing http services.

The steps of using. NET general host to build Silky microservice application are basically the same as using Web host to build microservice application. The difference is that there is no need to configure Startup class or http middleware (if configured, it is invalid); Developers can configure service injection by implementing IConfigureService interface.

1-2 steps and Building microservice applications using web hosts agreement.

  1. Building a silky host in the Main method
namespace Silky.Sample
{
    using Microsoft.Extensions.Hosting;
    using System.Threading.Tasks;
    class Program
    {
        public static async Task Main(string[] args)
        {
            await CreateHostBuilder(args).Build().RunAsync();
        }

        private static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
                    .ConfigureSilkyGeneralHostDefaults();
               
        }
    }
}

Create ConfigureService class to implement IConfigureService interface, and configure service injection dependency in ConfigureServices() method.

   public class ConfigureService : IConfigureService
    {
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            services.AddSilkySkyApm()
                //Other services (including third-party component services or other services of silky framework, such as Efcore component, MessagePack codec, Cap or MassTransit distributed event bus, etc.)
                //...
                ;
        }
    }

5-7 steps and Building microservice applications using web hosts agreement.

After starting the application, we can see the relevant log output on the console, and the application service is started successfully.

Users cannot directly access the microservice application. They must reference the application interface layer of the microservice through the gateway gateway The http service provided by indirectly accesses the services provided by the microservice application.

Constructing microservice application with websocket service capability

Developers build microservice applications with websocket service capabilities. Such microservice applications can not only serve as service providers, but also provide websocket communication capabilities (the default websocket port is 3000). Through handshake sessions with the server (through the gateway proxy), the server can realize the ability to push messages to customers.

Construction of microservice application with websocket service capability Using. NET general host to build microservice application The steps are the same, but the methods used to build microservice applications are different.

1-2 steps and Building microservice applications using web hosts agreement.

  1. Building a silky host in the Main method
namespace Silky.Sample
{
    using Microsoft.Extensions.Hosting;
    using System.Threading.Tasks;
    class Program
    {
        public static async Task Main(string[] args)
        {
            await CreateHostBuilder(args).Build().RunAsync();
        }

        private static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureSilkyWebSocketDefaults();
    }
}

Create ConfigureService class to implement IConfigureService interface, and configure service injection dependency in ConfigureServices() method.

   public class ConfigureService : IConfigureService
    {
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            services.AddSilkySkyApm()
                //Other services (including third-party component services or other services of silky framework, such as Efcore component, MessagePack codec, Cap or MassTransit distributed event bus, etc.)
                //...
                ;
        }
    }

5-6 steps and Building microservice applications using web hosts agreement.

  1. Build a service capable of providing websocket service

The definition of an application service interface is the same as that of a general application service. You only need to identify the [ServiceRoute] feature on a common interface.

[ServiceRoute]
public interface ITestAppService
{
   // Other methods (service entries) can be defined, and the defined methods can communicate with other micro service applications through the RPC framework
}

We need to install the Silky.WebSocket package in the application layer (Silky.Sample.Application).

PM> Install-Package Silky.WebSocket -Version 3.0.2

And add a TestAppService class to implement itetapservice. In addition, we need the TestAppService class to inherit the WsAppServiceBase base base class.

    public class TestAppService : WsAppServiceBase, ITestAppService
    {
        private readonly ILogger<TestAppService> _logger;

        public TestAppService(ILogger<TestAppService> logger)
        {
            _logger = logger;
        }

        // When establishing a websocket session
        protected override void OnOpen()
        {
            base.OnOpen();
            _logger.LogInformation("websocket established a session");
            
        }

        // When the service end receives the message from the customer service end
        protected override void OnMessage(MessageEventArgs e)
        {
            _logger.LogInformation(e.Data);
        }
        
       // When the websocket session is closed
        protected override void OnClose(CloseEventArgs e)
        {
            base.OnClose(e);
            _logger.LogInformation("websocket disconnected");
        }

        // Other service methods
    }

After starting the application, we can see the relevant log output on the console, and the application service is started successfully. The webapi address of the websocket service we defined is: / api/test.

  1. The client shakes hands with the websocket service through the gateway

The client cannot directly shake hands with the microservice application. It must reference the application interface layer of the microservice through the gateway gateway The websocket proxy service provided by is used to shake hands with the microservice through WS [S]: / / gateway_ ip[:gateway_port]/websocket_ The web API has a session with the previously defined websocket service.

In the built gateway application, we refer to the application interface layer of the microservice, start the gateway application (the gateway service address is 127.0.0.1:5000), and shake hands and communicate with the websocket service previously defined through the address: ws://127.0.0.1:5000/api/test.

When the client shakes hands with the websocket service, it needs to set the hashkey through the qstring parameter or the request header to ensure that the microservice application communicating each time is the same instance.

Building Silky microservice gateway

actually, Provide Web host through. net platform To build silky microservice applications, it can also be regarded as a gateway. The gateway and Provide Web host through. net platform The difference is that this type of microservice application can only be used as a service consumer, not a service provider or an RPC service provider.

Generally speaking, the gateway is an external traffic portal for the microservice application cluster.

Construction process and Provide Web host through. net platform Consistent, we only need to modify the method of creating the host to:

 private static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureSilkyGatewayDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });

By referring to the application interface layer of other microservice applications, the gateway project can be used as a service consumer to call the services provided by other microservice applications through the SilkyRPC framework. Through the http related middleware provided by the gateway, the online swagger document can be generated, the unified api authentication and http flow restriction can be realized, and the dashboard management end can be generated, Realize the health check of the instance of the service provider of the micro service cluster.

Open source address

Online documentation

Online example

Tags: Microservices

Posted on Wed, 03 Nov 2021 18:49:13 -0400 by ThunderAI