Microsoft Orleans——入门教程:Hello World
This overview ties into the Hello World sample application.
这篇概览与“Hello World”示例程序紧密相关。
The main concepts of Orleans involve a silo, a client, and one or more grains. Creating an Orleans app involves configuring the silo, configuring the client, and writing the grains.
Orleans 的核心概念主要包含三个部分:Silo(谷仓)、Client(客户端)以及一个或多个 Grain(谷物/实体)。创建一个 Orleans 应用,主要就是完成这三件事:配置 Silo、配置 Client,以及编写 Grain。
Configure the silo 配置 Silo
Configure silos programmatically via ISiloBuilder and several supplemental option classes. You can find a list of all options at List of options classes.
通过 ISiloBuilder 以及若干辅助选项类,可以以编程的方式来配置 Silo。你可以在“选项类列表(List of options classes)”中找到所有可用选项的清单。
public static async Task SiloMain(string[] args)
{
await Host.CreateDefaultBuilder(args)
.UseOrleans(siloBuilder =>
{
siloBuilder.UseLocalhostClustering()
.Configure<ClusterOptions>(options =>
{
options.ClusterId = "dev";
options.ServiceId = "HelloWorldApp";
})
.Configure<EndpointOptions>(
options => options.AdvertisedIPAddress = IPAddress.Loopback)
.ConfigureLogging(logging => logging.AddConsole());
})
.RunConsoleAsync();
}
The preceding code:
上述代码:
-
Creates a default host builder.
创建了一个默认的主机构建器(host builder)。
-
Calls UseOrleans to configure the silo.
调用 UseOrleans 来配置 Silo(容器)。
-
Uses localhost clustering for local development.
使用本地主机(localhost)集群,方便进行本地开发。
-
Configures the cluster and service IDs.
配置了集群 ID 和服务 ID。
-
Configures the endpoint to listen on loopback.
配置了监听回环地址(loopback)的终结点。
-
Adds console logging.
添加了控制台日志记录。
| Option 选项 | Used for 作用 |
|---|---|
.UseLocalhostClustering() |
Configures the client to connect to a silo on the localhost. 配置客户端去连接本地主机(localhost)上的 Silo。 |
| ClusterOptions |
ClusterId is the name for the Orleans cluster; it must be the same for the silo and client so they can communicate. ServiceId is the ID used for the application and must not change across deployments.
|
| EndpointOptions |
Tells the silo where to listen. For this example, use 告诉 Silo 在哪里进行监听。在这个示例中,我们使用的是回环地址(loopback)。 |
After loading the configurations, build the host and then start it asynchronously.
在加载完这些配置后,构建主机(host),然后以异步的方式启动它。
Configure the client 配置客户端
Similar to the silo, configure the client via IClientBuilder and a similar collection of option classes.
与配置 Silo(容器)类似,客户端也是通过 IClientBuilder 以及一系列类似的选项类来进行配置的。
public static async Task ClientMain(string[] args)
{
using IHost host = Host.CreateDefaultBuilder(args)
.UseOrleansClient(clientBuilder =>
{
clientBuilder.UseLocalhostClustering()
.Configure<ClusterOptions>(options =>
{
options.ClusterId = "dev";
options.ServiceId = "HelloWorldApp";
});
})
.ConfigureLogging(logging => logging.AddConsole())
.Build();
await host.StartAsync();
var client = host.Services.GetRequiredService<IClusterClient>();
Console.WriteLine("Client successfully connected to silo host");
await DoClientWork(client);
await host.StopAsync();
}
The preceding code:
上述代码:
-
Creates a default host builder.
创建了一个默认的主机构建器(host builder)。
-
Calls UseOrleansClient to configure the client.
调用 UseOrleansClient 来配置客户端。
-
Uses localhost clustering to connect to the local silo.
使用本地主机(localhost)集群来连接本地的 Silo。
-
Configures the cluster and service IDs to match the silo.
配置集群 ID 和服务 ID,确保与 Silo 的配置完全匹配。
-
Starts the host and retrieves the IClusterClient from the service provider.
启动主机,并从服务提供者(service provider)中获取 IClusterClient 实例。
| Option 选项 | Used for 作用 |
|---|---|
.UseLocalhostClustering() |
Same as for the silo 与 Silo 的配置作用相同。 |
| ClusterOptions |
Same as for the silo 与 Silo 的配置作用相同。 |
Find a more in-depth guide to configuring your client in the Client configuration section of the Configuration Guide.
如果想了解关于配置客户端的更详细指南,可以查看《配置指南》中的“客户端配置(Client configuration)”部分。
Write a grain 编写一个 Grain
Grains are the key primitives of the Orleans programming model. They are the building blocks of an Orleans application, serving as atomic units of isolation, distribution, and persistence. Grains are objects representing application entities. Just like in classic Object-Oriented Programming, a grain encapsulates an entity's state and encodes its behavior in code logic. Grains can hold references to each other and interact by invoking methods exposed via interfaces.
Grain 是 Orleans 编程模型中的关键基本单元。它们是构建 Orleans 应用的基石,作为隔离、分布式和持久化的原子单位而存在。Grain 本质上是代表应用程序实体的对象。就像在经典的面向对象编程(OOP)中一样,Grain 封装了实体的状态,并通过代码逻辑来体现其行为。Grain 之间可以互相持有引用,并通过调用接口中暴露的方法来进行交互。
Read more about them in the Grains section of the Orleans documentation.
你可以在 Orleans 文档的“Grains”部分阅读更多关于它们的详细介绍。
This is the main body of code for the Hello World grain:
下面就是“Hello World”这个 Grain 的主要代码逻辑:
public class HelloGrain : Orleans.Grain, IHello
{
private readonly ILogger<HelloGrain> _logger;
public HelloGrain(ILogger<HelloGrain> logger) => _logger = logger;
Task<string> IHello.SayHello(string greeting)
{
_logger.LogInformation("SayHello message received: greeting = '{Greeting}'", greeting);
return Task.FromResult($"You said: '{greeting}', I say: Hello!");
}
}
A grain class implements one or more grain interfaces. For more information, see the Grains section.
一个 Grain 类会实现一个或多个 Grain 接口。了解更多信息,请查看 Grains(谷物)部分。
public interface IHello : Orleans.IGrainWithIntegerKey
{
Task<string> SayHello(string greeting);
}
How the parts work together 各个部分是如何协同工作的
This programming model builds on the core concept of distributed Object-Oriented Programming. Start the ISiloHost first. Then, start the OrleansClient program. The Main method of OrleansClient calls the method that starts the client, StartClientWithRetries(). Pass the client to the DoClientWork() method.
这种编程模型建立在分布式面向对象编程的核心概念之上。首先启动 ISiloHost(容器主机)。然后,启动 OrleansClient(客户端)程序。OrleansClient 的 Main 方法会调用 StartClientWithRetries() 这个方法来启动客户端。最后,将建立好的客户端传递给 DoClientWork() 方法去执行具体的工作。
static async Task DoClientWork(IClusterClient client)
{
var friend = client.GetGrain<IHello>(0);
var response = await friend.SayHello("Good morning, my friend!");
Console.WriteLine($"\n\n{response}\n\n");
}
At this point, OrleansClient creates a reference to the IHello grain and calls its SayHello() method via the IHello interface. This call activates the grain in the silo. OrleansClient sends a greeting to the activated grain. The grain returns the greeting as a response to OrleansClient, which then displays it on the console.
此时,OrleansClient 会创建一个指向 IHello Grain 的引用,并通过 IHello 接口调用它的 SayHello() 方法。这次调用会直接在 Silo(容器)中激活对应的 Grain。随后,OrleansClient 向这个被激活的 Grain 发送一句问候语。Grain 收到后,会把问候语作为响应返回给 OrleansClient,客户端最终将其打印显示在控制台上。
Run the sample app 运行示例应用
To run the sample app, refer to the Readme.
要运行这个示例应用,请参考 Readme(自述文件/说明文档)。

浙公网安备 33010602011771号