如何在Akka Actor中实现receive() [英] How to implement receive () in Akka Actor

查看:461
本文介绍了如何在Akka Actor中实现receive()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Java代码中的Akka UntypedActors转换为它们的Scala等效项。

I am in the process of converting Akka UntypedActors in Java code to their Scala equivalent.

但是,我在理解如何正确实现receive()时遇到麻烦抽象方法。 ScalaDoc有点令人困惑,我看到的大多数示例都只涉及字符串消息!

However, I am having trouble understanding how to correctly implement the receive() abstract method. The ScalaDoc is a little confusing and most of the examples I see just involve String messages!

我的Actor可以支持多种消息类型,到目前为止,这是我的解决方案:

My Actor can support multiple message types and this is my solution so far:

override def receive = {
    case message if message.isInstanceOf[ClassOne] => {
        // do something after message.asInstanceOf[ClassOne]
      }
    case message if message.isInstanceOf[ClassTwo] => {
      // do something after message.asInstanceOf[ClassTwo]
    }        
    case message => unhandled(message)
  }

是否有更好的方法来实现上述目标?

Is there a better way to achieve the above?

推荐答案

接收的类型实际上只是一个 PartialFunction [Any,Unit] ,这意味着您可以使用Scala的模式匹配表达式-实际上,您已经在这么做了,只是不完全简洁。等效的简短处理也可以让您处理每种情况的匹配类型:

receive's type is really just a PartialFunction[Any,Unit], which means you can use Scala's pattern match expressions - in fact, you're already doing it, just not entirely succinctly. A terser equivalent that would also let you handle the type of the match for each case:

def receive = {
    case classOneMessage : ClassOne => {
        // do something
      }
    case classTwoMessage : ClassTwo => {
      // do something 
    }        
    case _ => someCustomLogicHereOtherWiseThereWillBeASilentFailure 
              //you can, but you don't really need to define this case - in Akka 
              //the standard way to go if you want to process unknown messages
              //within *this* actor, is to override the Actor#unhandled(Any) 
              //method instead
  }

阅读旅游文章 ,以及已链接的教程以了解更多信息模式匹配的信息,尤其是在将功能与案例类一起使用的情况下-在使用Akka时会定期应用此模式,例如此处位于Akka手册中处理 ActorIdentity 案例类

Read the tour article, and the already-linked tutorial for more info on pattern matching, especially in the context of using the feature together with case classes - this pattern is applied regularly when working with Akka, for example here in the Akka manual when handling the ActorIdentity case class.

这篇关于如何在Akka Actor中实现receive()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆