Fork me on GitHub

《通过C#学Proto.Actor模型》之Mailbox

邮箱是Actor模型的一个重要组成部分,负责接收发过来的消息,并保存起来,等待Actor处理。邮箱中维护着两种队列,一种是存系统消息,另一个是存用户消息,系统省是指Started,Stoping,Stoped之类的,用户当然指我们自定义的Actor。

另外,我们可以通过实现IMailboxStatistics接口,来获取邮箱的状态变更,并且可以有多个IMailboxStatistics实现。

 

码友看代码:

 1 using Proto;
 2 using Proto.Mailbox;
 3 using System;
 4 using System.Threading.Tasks;
 5 
 6 namespace P005_Mailboxes
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             var props = new Props()
13                 // 用道具代理返回一个IActor实例
14                 .WithProducer(() => new MyActor())
15                 //默认邮箱使用无界队列
16                 .WithMailbox(() => UnboundedMailbox.Create(new MyMailboxStatistics()))
17                 // 默认的 spawner 构造  Actor, Context 和 Process
18                 .WithSpawner(Props.DefaultSpawner);
19 
20             //从props衍生pid,pid代理一个actor的地址
21             var pid = Actor.Spawn(props);
22             //把Hello对象交给HelloActor处理
23             pid.Tell(new MyEntity
24             {
25                 Message = "this is message"
26             });
27             Console.ReadLine();
28         }
29     }
30     public class MyActor : IActor
31     {
32         public Task ReceiveAsync(IContext context)
33         {
34             if (context.Message is MyEntity myEntity)
35             {
36                 Console.WriteLine(myEntity.Message);
37             }
38             return Actor.Done;
39         }
40     }
41     public class MyEntity
42     {
43         public string Message { get; set; }
44     }
45     public class MyMailboxStatistics : IMailboxStatistics
46     {
47         public void MailboxEmpty()
48         {            
49             Console.WriteLine("邮箱MailboxEmpty");
50         }
51 
52         public void MailboxStarted()
53         {
54             Console.WriteLine("邮箱MailboxStarted");
55         }
56 
57         public void MessagePosted(object message)
58         {
59             Console.WriteLine("邮箱MessagePosted:"+message);
60         }
61 
62         public void MessageReceived(object message)
63         {
64             Console.WriteLine("邮箱MessageReceived:"+message);
65         }
66     }
67 }

当消息Posted时,Started时,Received时,邮箱为空时,这些方法会被先后调用,这里可对消息作处理。

posted @ 2018-08-30 08:35  桂素伟  阅读(994)  评论(2编辑  收藏  举报