Aprender Orleans 02 - Hello World

conceptos básicos

Orleans es el concepto básico se muestra arriba.

- https://www.cnblogs.com/sheng-jie/p/11223848.html

- https://github.com/sheng-jie/Samples.AllInOne/tree/dev/Orleans

Grano es un actor, es la unidad más pequeña de la ejecución. Silo es un tiempo de ejecución Orleáns por acoger granos. Silo un grupo capaz de formar un clúster distribuido, y puede ser tolerante a fallos.

- https://dotnet.github.io/orleans/Documentation/index.html

En Orleans, grano contiene la identidad, la conducta y un componentes de estado opcionales.

ciclo de vida del grano gestionado por el tiempo de ejecución, el estado cambia como se muestra a continuación:

Hola Mundo

https://dotnet.github.io/orleans/Documentation/tutorials_and_samples/tutorial_1.html

proyecto Orleans Hello World consta de cuatro componentes:

  1. interfaces de grano
  2. clases de granos
  3. silo de anfitrión
  4. consola del cliente

En primer lugar, crear una estructura de proyecto

dotnet new console -n Silo
dotnet new console -n Client
dotnet new classlib -n GrainInterfaces
dotnet new classlib -n Grains
dotnet new sln -n OrleansHelloWorld
dotnet sln add Silo Client GrainInterfaces Grains

Dependencias proporcionan cuatro elementos como se muestra arriba.

A continuación, añadir el paquete requerido Nuget

#silo
dotnet add package Microsoft.Orleans.Server
dotnet add package Microsoft.Extensions.Logging.Console
#client
dotnet add package Microsoft.Orleans.Client 
dotnet add package Microsoft.Extensions.Logging.Console
#GrainInterfaces
dotnet add package Microsoft.Orleans.Core.Abstractions 
dotnet add package Microsoft.Orleans.CodeGenerator.MSBuild
#Grains
dotnet add package Microsoft.Orleans.Core.Abstractions
dotnet add package Microsoft.Orleans.CodeGenerator.MSBuild
dotnet add package Microsoft.Extensions.Logging.Abstractions

La creación de la interfaz grano

IHello.cs

using System.Threading.Tasks;

namespace OrleansBasics
{
    public interface IHello : Orleans.IGrainWithIntegerKey
    {
        Task<string> SayHello(string greeting);
    }
}

La creación de la clase de grano

HelloGrain.cs

using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace OrleansBasics
{
    public class HelloGrain : Orleans.Grain, IHello
    {
        private readonly ILogger logger;

        public HelloGrain(ILogger<HelloGrain> logger)
        {
            this.logger = logger;
        }

        Task<string> IHello.SayHello(string greeting)
        {
            logger.LogInformation($"\n SayHello message received: greeting = '{greeting}'");
            return Task.FromResult($"\n Client said: '{greeting}', so HelloGrain says: Hello!");
        }
    }
}

Silo - Program.cs

using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;

namespace OrleansBasics
{
    public class Program
    {
        public static int Main(string[] args)
        {
            return RunMainAsync().Result;
        }

        private static async Task<int> RunMainAsync()
        {
            try
            {
                var host = await StartSilo();
                Console.WriteLine("\n\n Press Enter to terminate...\n\n");
                Console.ReadLine();

                await host.StopAsync();

                return 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return 1;
            }
        }

        private static async Task<ISiloHost> StartSilo()
        {
            // define the cluster configuration
            var builder = new SiloHostBuilder()
                .UseLocalhostClustering()
                .Configure<ClusterOptions>(options =>
                {
                    options.ClusterId = "dev";
                    options.ServiceId = "OrleansBasics";
                })
                .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(HelloGrain).Assembly).WithReferences())
                .ConfigureLogging(logging => logging.AddConsole());

            var host = builder.Build();
            await host.StartAsync();
            return host;
        }
    }
}

Cliente - Program.cs

using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Configuration;
using System;
using System.Threading.Tasks;

namespace OrleansBasics
{
    public class Program
    {
        static int Main(string[] args)
        {
            return RunMainAsync().Result;
        }

        private static async Task<int> RunMainAsync()
        {
            try
            {
                using (var client = await ConnectClient())
                {
                    await DoClientWork(client);
                    Console.ReadKey();
                }

                return 0;
            }
            catch (Exception e)
            {
                Console.WriteLine($"\nException while trying to run client: {e.Message}");
                Console.WriteLine("Make sure the silo the client is trying to connect to is running.");
                Console.WriteLine("\nPress any key to exit.");
                Console.ReadKey();
                return 1;
            }
        }

        private static async Task<IClusterClient> ConnectClient()
        {
            IClusterClient client;
            client = new ClientBuilder()
                .UseLocalhostClustering()
                .Configure<ClusterOptions>(options =>
                {
                    options.ClusterId = "dev";
                    options.ServiceId = "OrleansBasics";
                })
                .ConfigureLogging(logging => logging.AddConsole())
                .Build();

            await client.Connect();
            Console.WriteLine("Client successfully connected to silo host \n");
            return client;
        }

        private static async Task DoClientWork(IClusterClient client)
        {
            // example of calling grains from the initialized client
            var friend = client.GetGrain<IHello>(0);
            var response = await friend.SayHello("Good morning, HelloGrain!");
            Console.WriteLine("\n\n{0}\n\n", response);
        }
    }
}

Ejecutar:

En primer lugar empezar Silos reinicio de clientes, de la siguiente manera:

Supongo que te gusta

Origin www.cnblogs.com/wswind/p/12549822.html
Recomendado
Clasificación