.NET分佈式Orleans - 2 - Grain的通信原理與定義

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 接口,併爲其增加了買裝備的動作,並將買完的裝備保存至內存中:

public interface IPlayerGrain : IGrainWithStringKey
{
    Task BuyEquipment(string equipmentName);
    Task<List<string>> GetOwnedEquipments();
}

public class PlayerGrain : Grain, IPlayerGrain
{
    private IPersistentState<List<string>> _ownedEquipments;

    public PlayerGrain([PersistentState("ownedEquipments", "playerGrainStorage")] IPersistentState<List<string>> ownedEquipments)
    {
        _ownedEquipments = ownedEquipments;
    }


    public async override Task OnActivateAsync(CancellationToken cancellationToken)
    {
        await base.OnActivateAsync(cancellationToken);

        // 在激活時從持久化狀態中加載數據
        await _ownedEquipments.ReadStateAsync();
        if (_ownedEquipments.State == null)
        {
            _ownedEquipments.State = new List<string>();
            await _ownedEquipments.WriteStateAsync(); // 將空列表持久化到存儲中
        }
    }

    public async 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 和執行其他集羣操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章