Implementation method of carrying eshop on containers with service fabric

Time:2020-6-29

From pet shop to eshop on container are sample projects in which Microsoft demonstrates. Net’s development ability and architecture ability to developers on the path of technology evolution. When petshop is used, it is more about application’s layered architecture, design abstraction and communication between modules. Now that eshop on container focuses more on architecture design and microservice, let’s take a look at the architecture diagram of eshop on container

In the figure above, we can see that the back-end services are divided into

1 identity microservice

2 catalog microservice

3 ordering microservice

4 basket microservice

5 marketing microservice

6 locations microservice

What the services are the first mock exam in the previous hierarchical architecture, and why are they now split into services? When we look at these services from the business scenario, we will find that the peak access time interval and capacity planning of each service are different, and even the most convenient and simplest technology stack for implementing these services may be different (of course, the powerful. Net Core is omnipotent, but the technology reserves of different business lines in the company are different, so it is possible to choose different technologies for Implementation). This is because if we integrate these modules into a program or service, we will encounter difficulties in expanding system capacity during peak service periods at different times, either due to insufficient resources or excessive resources. For example, before the start of the rush purchase business, everyone logged in to the system one and a half hours in advance. At this time, the system’s busiest is the login module, and when it comes to the rush purchase time, the system’s busiest is the order module. Without the micro service architecture, the resources prepared for the login module half an hour ago may not be released to the order module in time. If both modules use a single program architecture, the most likely situation is that the rush to buy business has occupied all resources, even other normal access system user resources have been occupied, resulting in system crash. In today’s dev / OPS era, developers and architects need to think more about the impact of hardware architecture on application.

The first way to use service fabric to carry eshop on container microservices is to directly manage dockers through service fabric

First, we apply for a container registry on azure to host the image of various eshop microservices. To create an azure docker registry, please refer to the official document: https://docs.microsoft.com/zh-cn/azure/container-registry/

Now the latest version of service fabric can directly manage the choreographer.

1. Create a service of type container

image

2. In servicemanifest.xml The path of image is described clearly in


<CodePackage Name="Code" Version="1.0.0">
 <!-- Follow this link for more information about deploying Windows containers to Service Fabric: https://aka.ms/sfguestcontainers -->
 <EntryPoint>
 
  <ContainerHost>
  <ImageName>eshopsample.azurecr.io/catalog:latest</ImageName>  
  </ContainerHost>  
 </EntryPoint>
 <!-- Pass environment variables to your container: --> 
 <EnvironmentVariables>
  <EnvironmentVariable Name="HttpGatewayPort" Value=""/>
 </EnvironmentVariables>
 </CodePackage>

This is very simple. It is good to specify the location of the image. If you need a lot of configuration information in docker image, such as database link string, address of other services, etc., you can configure it in environment variables.

3. To configure the access account and password of registry, you need to ApplicationManifest.xml Configure it from the top


<ServiceManifestImport>
 <ServiceManifestRef ServiceManifestName="CatalogService_Pkg" ServiceManifestVersion="1.0.1" />  
 <Policies>
  <ContainerHostPolicies CodePackageRef="Code" Isolation="hyperv">
  <RepositoryCredentials AccountName="youraccount" Password="xxxxxxxxxxxxx" PasswordEncrypted="false"/>
  <PortBinding ContainerPort="80" EndpointRef="CatalogServieEndpoint"/>
  
  </ContainerHostPolicies>
 </Policies>
 </ServiceManifestImport>

The whole process will not be too complicated, as long as the catalog microservice is configured ServiceManifest.xm and ApplicationManifest.xml After the file, we can use the same method to configure other services one by one, and then we can publish the configuration of service fabric to the cluster.

image

The service fabric will automatically pull image on the cluster and run docker according to the configuration. It’s simple

The second method is to use the runtime of service fabric to run eshop on container microservices

Service fabric itself is a microservice development framework. Now it directly supports. Net core 2.0. Therefore, after we update the service fabric SDK, we can directly create. Net core services

imageimage

The code of eshop on container is a formed. Net core 2.0 code, so there is no need to rewrite the service.

1. Add the latest service fabric and the latest SDK through nuget.

image

2. Modification programe.cs To start the servicefabric runtime instead of starting it directly Asp.net WebHost

public static void Main(string[] args)
  {
   try
   {
    // ServiceManifest.XML  The file defines one or more service type names.
    //Registering a service maps the service type name to a. Net type.
    //When the service fabric creates an instance of this service type,
    //An instance of the class is created in this host process.
    ServiceRuntime.RegisterServiceAsync("Catalog.API",
     context => new CatalogAPI(context)).GetAwaiter().GetResult();
    ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(CatalogAPI).Name);
    //Prevent this host process from terminating to keep the service running. 
    Thread.Sleep(Timeout.Infinite);
   }
   catch (Exception e)
   {
    ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
    throw;
   }
}

3. Compilation

The catalogapi class is used to start webhost


internal sealed class CatalogAPI : StatelessService
 {
  public CatalogAPI(StatelessServiceContext context)
   : base(context)
  { }
  /// <summary>
  /// Optional override to create listeners (like tcp, http) for this service instance.
  /// </summary>
  /// <returns>The collection of listeners.</returns>
  protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
  {
   return new ServiceInstanceListener[]
   {
    new ServiceInstanceListener(serviceContext =>
     new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
     {
      ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting WebListener on {url}");
            return new WebHostBuilder()
           .UseKestrel()
         .ConfigureServices(
          services => services
           .AddSingleton<StatelessServiceContext>(serviceContext))
         .UseContentRoot(Directory.GetCurrentDirectory())
         .ConfigureAppConfiguration((builderContext, config) =>
         {
          IHostingEnvironment env = builderContext.HostingEnvironment;
          config.AddJsonFile("settings.json", optional: false, reloadOnChange: true)
           .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
          
         })
         .UseStartup<Startup>()
         .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
         .UseUrls(url)
         .UseWebRoot("Pics")
         .Build();     
     }))
   };
  }
 }

4. Compilation serviceManifest.xml Describe the service port and other information


<?xml version="1.0" encoding="utf-8"?>
<ServiceManifest Name="Catalog.APIPkg"
     Version="1.0.3"
     xmlns="http://schemas.microsoft.com/2011/01/fabric"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <ServiceTypes>
  <StatelessServiceType ServiceTypeName="Catalog.API" />
 </ServiceTypes>
 <!-- Code package is your service executable. -->
 <CodePackage Name="Code" Version="1.0.3">
 <EntryPoint>
  <ExeHost>
  <Program>Catalog.API.exe</Program>
  <WorkingFolder>CodePackage</WorkingFolder>
  </ExeHost>
 </EntryPoint>
 <EnvironmentVariables>
  <EnvironmentVariable Name="ASPNETCORE_ENVIRONMENT" Value="Development"/>
 </EnvironmentVariables>
 </CodePackage>

 <ConfigPackage Name="Config" Version="1.0.1" />
 <Resources>
 
 <Endpoints> 
 
  <Endpoint Protocol="http" Name="ServiceEndpoint" Type="Input" Port="5101" />
 </Endpoints>
 </Resources>
</ServiceManifest>

5. Modification AppcationManifest.xml Add descriptions of several services

Add ServiceImport section


<ServiceManifestImport>
 <ServiceManifestRef ServiceManifestName="Catalog.APIPkg" ServiceManifestVersion="1.0.3" />
 <ConfigOverrides />
 </ServiceManifestImport>

Describe service in defaultservice


<Service Name="Catalog.API" ServiceDnsName="catalog.fabric.api">
  <StatelessService ServiceTypeName="Catalog.API" InstanceCount="[Catalog.API_InstanceCount]">
  <SingletonPartition />
  </StatelessService>
 </Service>

In this way, we can transform the catalog service into a microservice that can be managed through the service fabric. Through publish, we can see that several services have been managed and choreographed under the service fabric.

image

visit localhost:5100

image

The above implementation method of using service fabric to carry eshop on containers is to edit all the content shared with you. I hope it can give you a reference, and I hope you can support developeppaer more.