Orleans[NET Core 3.1] 學習筆記(二)Hello World

項目結構

開始Orleans以前,咱們都知道Orleans主要能夠分爲倆部分,Host和Client。
因此咱們能夠建立以下的項目結構:

IGrain 一個包含Grain接口的庫(.NET Standard 2.1)
Grain 一個包含Grain類的庫(.NET Standard 2.1)
Host 一個控制檯應用程序,用來託管咱們的Silo(.NET Core 3.1)
Client 一個控制檯應用程序,用來作咱們的Orleans客戶端(.NET Core 3.1)html

Orleans引用

NuGet咋用不用我再贅述了吧。git

IGraingithub

Microsoft.Orleans.Core.Abstractions(3.0.1)
Microsoft.Orleans.CodeGenerator.MSBuild(3.0.1)

Grain服務器

Microsoft.Orleans.Core.Abstractions(3.0.1)
Microsoft.Orleans.CodeGenerator.MSBuild(3.0.1)
Microsoft.Extensions.Logging.Abstractions(3.1.0)//用於日誌記錄

Hostasync

Microsoft.Orleans.Server(3.0.1)
Microsoft.Extensions.Logging.Console(3.1.0)//用於控制檯信息打印

Client分佈式

Microsoft.Orleans.Client(3.0.1)
Microsoft.Extensions.Logging.Console(3.1.0)//用於控制檯信息打印

定義Grain接口

在IGrain項目中,添加一個IHello.cs代碼文件,並在其中定義如下IHello接口:ide

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

namespace Grain
{
    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消息: greeting = '{greeting}'");
            return Task.FromResult($"\n Client said: '{greeting}', so HelloGrain says: Hello!");
        }
    }
}

建立Silo

在這一步,咱們修改Host的Program.cs以初始化託管和運行咱們的Grain服務器-Silo。在這裏咱們用代碼來控制羣集和鏈接,實際應用的配置能夠在Orleans文檔的「 本地開發配置」頁面中找到更多的信息。如今的例子只是運行具備單個Silo的集羣。學習

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

namespace Host
{
    class Program
    {
        static int Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            return RunMainAsync().Result;
        }

        private static async Task<int> RunMainAsync()
        {
            try
            {
                var host = await StartSilo();
                Console.WriteLine("\n\n 按回車鍵中止 \n\n");
                Console.ReadLine();

                await host.StopAsync();

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

        private static async Task<ISiloHost> StartSilo()
        {
            //定義羣集配置
            var builder = new SiloHostBuilder()
                .UseLocalhostClustering()//配置Silo只使用開發集羣,並監聽本地主機
                .Configure<ClusterOptions>(options =>
                {
                    options.ClusterId = "dev";//獲取或設置羣集標識。這在Orleans 2.0名稱以前曾被稱爲DeploymentId。
                    options.ServiceId = "OrleansBasics";//獲取或設置此服務的惟一標識符,該標識符應在部署和從新部署後繼續存在,其中Orleans.Configuration.ClusterOptions.ClusterId可能不存在。
                })
                .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(HelloGrain).Assembly).WithReferences())
                .ConfigureLogging(logging => logging.AddConsole());

            var host = builder.Build();//運行給定的配置來初始化主機。只能調用一次。
            await host.StartAsync();//啓動當前Silo.
            return host;
        }
    }
}

建立客戶端

最後,咱們須要配置一個客戶端與Grain進行通訊,將其鏈接到集羣(其中有一個Silo),而後調用Grain。注意,羣集配置必須與咱們用於Silo的配置匹配。在Orleans文檔的「 羣集和客戶端」中有關於客戶端的更多配置信息ui

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

namespace Client
{
    class Program
    {
        static int Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            return RunMainAsync().Result;
        }

        private static async Task<int> RunMainAsync()
        {
            try
            {
                using(var client = await ConnectClient())
                {
                    await DoClientWork(client);
                    Console.ReadKey();
                }
                return 0;
            }
            catch(Exception ex)
            {
                Console.WriteLine($"\n嘗試運行客戶端時發生異常: {ex.Message}");
                Console.WriteLine("請確保客戶端嘗試鏈接的 Silo Host 正在運行。");
                Console.WriteLine("\n按任意鍵退出。");
                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("客戶端已成功鏈接到Silo Host  \n");
            return client;
        }

        private static async Task DoClientWork(IClusterClient client)
        {
            //從客戶端調用Grain的示例
            var friend = client.GetGrain<IHello>(0);
            var response = await friend.SayHello("Good morning, HelloGrain!");
            Console.WriteLine("\n\n{0}\n\n", response);
        }

    }
}

運行應用程序

Hostthis

Client

本文代碼範例

GitHub倉庫

便捷路由

目錄Orleans[NET Core 3.1] 學習筆記(一).NET環境下的分佈式應用程序
下一節Orleans[NET Core 3.1] 學習筆記(三)( 1 )本地開發配置

相關文章
相關標籤/搜索