本教程旨在介绍如何使用Akka.NET 创建一个简单的问候Actor ,使用C# 语言。
项目设置
启动visual studio 并新建一个 C# 控制台程序.
建好后,打开包管理器控制台(Package Manager Console),键入:
1
| PM> Install-Package Akka
|
然后我们需要添加相关语句:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
using Akka; using Akka.Actor;
namespace ConsoleApplication11 { class Program { static void Main(string[] args) { } } }
|
创建第一个actor
首先,我们要创建消息类型(Greet 类)以使Actor 去响应:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
using Akka; using Akka.Actor;
namespace ConsoleApplication11 { public class Greet { public Greet(string who) { Who = who; } public string Who { get;private set; } }
class Program { static void Main(string[] args) { } } }
|
建好后,开始建actor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
using Akka; using Akka.Actor;
namespace ConsoleApplication11 { public class Greet { public Greet(string who) { Who = who; } public string Who { get;private set; } }
public class GreetingActor : ReceiveActor { public GreetingActor() { Receive<Greet>(greet => Console.WriteLine("Hello {0}", greet.Who)); } }
class Program { static void Main(string[] args) { } } }
|
现在,是时候消费Actor了, 我们通过创建 ActorSystem
实例和使用 ActorOf
方法来实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
using Akka; using Akka.Actor;
namespace ConsoleApplication11 { public class Greet { public Greet(string who) { Who = who; } public string Who { get;private set; } }
public class GreetingActor : ReceiveActor { public GreetingActor() { Receive<Greet>(greet => Console.WriteLine("Hello {0}", greet.Who)); } }
class Program { static void Main(string[] args) { var system = ActorSystem.Create("MySystem");
var greeter = system.ActorOf<GreetingActor>("greeter");
greeter.Tell(new Greet("World"));
Console.ReadLine(); } } }
|
就是这样,你的Actor 现在已经准备好接收从任意调用线程发送的消息了。