zoukankan      html  css  js  c++  java
  • 《通过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时,邮箱为空时,这些方法会被先后调用,这里可对消息作处理。

  • 相关阅读:
    Ext.net中Combobox如何绑定数据库中的值-通用方法
    Tree通用的系列方法列表-treepanel
    这个时代“寒门再难出贵子” (转帖)
    java 文件保存到本地
    bootsrap的font awesome的各种图标,包括动画图标
    去除html的 标签
    Java从网络读取图片并保存至本地
    java正则表达式获得html字符串中<img src>的src中的url地址
    解决IDEA自动重置LanguageLevel和JavaCompiler版本的问题
    JAVA-JSP内置对象之page对象调用Servlet
  • 原文地址:https://www.cnblogs.com/axzxs2001/p/9558040.html
Copyright © 2011-2022 走看看