當前位置: 妍妍網 > 碼農

.NET分布式Orleans - 2 - Grain的通訊原理與定義

2024-03-25碼農

Grain 是 Orleans 框架中的基本單元,代表了應用程式中的一個實體或者一個計算單元。

每個Silo都是一個獨立的行程,Silo負責載入、管理和執行Grain例項,並處理來自客戶端的請求以及與其他Silo之間的通訊。

通訊原理

在相同的Silo中,Grain與Grain之間的通訊透過直接的方法呼叫實作。每個Silo都維護了一個Grain的執行時環境,當一個Grain需要呼叫另一個Grain時,它可以直接呼叫目標Grain的方法,無需經過網路傳輸,示意圖如下所示:

在不同的Silo中,Grain與Grain之間的通訊需要透過訊息傳遞的方式實作。當一個Grain需要與另一個Silo中的Grain通訊時,它會將訊息發送給目標Grain所在的Silo,目標Silo接收到訊息後,將其路由到目標Grain,然後目標Grain處理訊息並返回結果。示意圖如下所示:

外部客戶端與Silo之間的通訊是透過網路訊息傳輸實作的。客戶端需要使用Orleans提供的客戶端庫與Silo建立連線,並行送請求訊息到目標Silo,目標Silo接收到訊息後,進行處理並返回結果。在Orleans中,客戶端與Silo之間的通訊使用了一種名為Orleans Messaging Protocol (OMP)的自訂協定,用於保證通訊的可靠性和效率。示意圖如下所示:

內建埠

預設情況下,Orleans 將偵聽埠 11111 用於silo之間通訊,在埠 30000 上進行客戶端到接收器通訊。可以透過以下方式設定這些埠

siloBuilder.Configure<EndpointOptions>(options =>{// Port to use for silo-to-silo options.SiloPort = 11_111;// Port to use for the gateway options.GatewayPort = 30_000;// IP Address to advertise in the cluster options.AdvertisedIPAddress = IPAddress.Parse("172.16.0.42");// The socket used for client-to-silo will bind to this endpoint options.GatewayListeningEndpoint = new IPEndPoint(IPAddress.Any, 40_000);// The socket used by the gateway will bind to this endpoint options.SiloListeningEndpoint = new IPEndPoint(IPAddress.Any, 50_000);})

在內部,silo 將偵聽 0.0.0.0:40000 和 0.0.0.0:50000,但在持久化提供程式中釋出的值將是 172.16.0.42:11111 和 172.16.0.42:30000

GrainKey型別

在 Orleans 中,可以使用不同型別的鍵來標識 Grain。下面是幾種常用的 GrainKey 介面:

  • IGrainWithStringKey: 使用字串作為鍵的介面。適用於需要以字串形式標識的場景,比如使用者名稱稱、訂單號等。

  • IGrainWithGuidKey: 使用 Guid 作為鍵的介面。適用於需要全域唯一標識的場景,比如唯一的實體物件、全域唯一的識別元等。

  • IGrainWithIntegerKey: 使用整數作為鍵的介面。適用於需要連續遞增或遞減的序列標識的場景,比如自增主鍵、序列號等。

  • IGrainWithGuidCompoundKey: 使用復合的 Guid 作為鍵的介面。

  • IGrainWithIntegerCompoundKey: 使用復合的整數作為鍵的介面。

  • IGrainWithGuidCompoundKey: 使用復合的字串作為鍵的介面。

  • 下面是使用 IGrainWithStringKey 定義的 IPlayerGrain 介面,並為其增加了買裝備的動作,並將買完的裝備保存至記憶體中:

    publicinterfaceIPlayerGrain : IGrainWithStringKey{Task BuyEquipment(string equipmentName); Task<List<string>> GetOwnedEquipments();}public classPlayerGrain : Grain, IPlayerGrain{private IPersistentState<List<string>> _ownedEquipments;publicPlayerGrain([PersistentState("ownedEquipments", "playerGrainStorage")] IPersistentState<List<string>> ownedEquipments) { _ownedEquipments = ownedEquipments; }publicasyncoverride Task OnActivateAsync(CancellationToken cancellationToken) {awaitbase.OnActivateAsync(cancellationToken);// 在啟用時從持久化狀態中載入數據await _ownedEquipments.ReadStateAsync();if (_ownedEquipments.State == null) { _ownedEquipments.State = new List<string>();await _ownedEquipments.WriteStateAsync(); // 將空列表持久化到儲存中 } }publicasync Task BuyEquipment(string equipmentName) { _ownedEquipments.State.Add(equipmentName);await _ownedEquipments.WriteStateAsync(); // 將更新後的裝備列表持久化到儲存中 }public Task<List<string>> GetOwnedEquipments() {return Task.FromResult(_ownedEquipments.State); }}

    呼叫時使用IGrainFactory.GetGrain方法即可

    var host = Host.CreateDefaultBuilder() .ConfigureServices((context, services) => { services.AddOrleans(builder => { builder .UseLocalhostClustering() .Configure<ClusterOptions>(options => { options.ClusterId = "dev"; options.ServiceId = "OrleansExample"; }) .AddMemoryGrainStorage("playerGrainStorage"); }); }) .ConfigureLogging(l => l.AddConsole()) .Build();await host.StartAsync();var client = host.Services.GetRequiredService<IGrainFactory>();var palyer = client.GetGrain<IPlayerGrain>(Guid.NewGuid().ToString());await palyer.BuyEquipment("Sword");(await palyer.GetOwnedEquipments()).ForEach(Console.WriteLine);

    IGrainFactory 和 IClusterClient

    在 Orleans 中,IGrainFactory 和 IClusterClient 都是用於建立和獲取 Grains 的介面,但它們的作用和使用場景略有不同。

    IGrainFactory:

    IGrainFactory 是 Orleans 用於集群中建立 Grains 的工廠介面。它通常用於在 Orleans Silo 或者 Orleans Client 中建立 Grains 例項。

  • 在 Silo 中,您可以透過依賴註入或者直接例項化一個 IGrainFactory 物件來建立 Grains。

  • 在 Silo 外部,比如 Orleans Client 中,您也可以透過依賴註入或者直接例項化一個 IGrainFactory 物件來建立 Grains。

  • // 透過依賴註入或直接例項化一個 IGrainFactory 物件IGrainFactory grainFactory = serviceProvider.GetRequiredService<IGrainFactory>();var grain = grainFactory.GetGrain<IMyGrain>(grainId);

    IClusterClient:

    IClusterClient 是 Orleans 中用於與 Orleans 集群進行通訊的客戶端介面。它通常在 Orleans Client 中使用,用於與 Orleans Silo 進行通訊,以呼叫 Grains 的方法或者獲取 Grains 的參照。

    IClusterClient 是 IGrainFactory 的一個超集,除了可以建立 Grains,還可以執行其他集群相關的操作,比如管理 Silo 的生命周期、訂閱集群中的事件等。

    // 透過依賴註入或直接例項化一個 IClusterClient 物件IClusterClient clusterClient = serviceProvider.GetRequiredService<IClusterClient>();var grain = clusterClient.GetGrain<IMyGrain>(grainId);

    總的來說,IGrainFactory 主要用於在應用程式內部直接建立 Grains,而 IClusterClient 則更適合用於外部Client與 Orleans 集群進行通訊,包括建立 Grains 和執行其他集群操作。

    關註獲取技術分享