java - Akka Java setReceiveTimeout 用法

标签 java timeout akka

我正在查看关于未类型化 actor 的 Akka Java 文档 (http://doc.akka.io/docs/akka/2.3.2/java/untyped-actors.html)

我实际上想完成一些事情,例如:

为我希望在 onReceive() 方法中收到的任何特定消息设置超时。例如:

 public void onReceive(Object message) throws Exception {

     if (message.equals("start")) {
        child.tell("fetch something for me!", getSelf());
     }

     if (message.equals("child's response")) {
        // handle a response from a child here,
        // but timeout within some timeframe if I don't get a 
        // response quick enough.
       // use this here? getContext().setReceiveTimeout(Duration.create("1 second"));
     }
 }

我知道您可以使用返回 future 的 Patterns.ask(actor, message, timeout)。如果在指定的超时参数内未发回响应,则失败。

我不想在这里使用 future 。我不明白 setReceiveTimeout 方法的用法。我如何通过纯粹使用 actor.tell 来实现这一点?

最佳答案

您应该在向其他参与者执行tell 后立即设置接收超时。一旦你这样做了,时钟基本上就会开始滴答作响。如果此 actor 在该时间范围内未在其邮箱中收到任何消息,则 ReceiveTimeout 消息将被放入邮箱中,指示您未及时收到响应。解决此问题的更新代码版本如下所示:

public void onReceive(Object message) throws Exception {

    if (message.equals("start")) {
        child.tell("fetch something for me!", getSelf());
        getContext().setReceiveTimeout(Duration.create("1 second"));
    }

    else if (message.equals("child's response")) {
        getContext().setReceiveTimeout(Duration.Undefined()); //turn off receive timeout
        // handle a response from a child here
    }

    else if (message instanceof ReceiveTimeout) {
        getContext().setReceiveTimeout(Duration.Undefined()); //turn off receive timeout
        // handle situation where I did not get a response in time
    }
 }

您会注意到,无论我得到实际响应还是接收超时,我总是关闭在 tell 之后设置的接收超时。接收超时重复;如果我没有明确关闭它,它将继续在每个时间间隔向我发送 ReceiveTimeout 消息(基于我设置接收超时时的时间间隔)。

请务必牢记,接收超时功能与消息无关。也就是说,如果我的邮箱收到任何消息,它会被跳过一段时间;不只是我想要的那个。因此,如果其他 Actor 向我发送了另一条完全不同的消息,它将跳过该时间间隔的接收超时。如果这不会成为问题,则无需担心。但是如果除了响应之外还有其他消息可能到达,您将需要相应地处理,根据最初设置后耗时重置原始接收超时(可能通过 Deadline 实例。

关于java - Akka Java setReceiveTimeout 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23533757/

相关文章:

java - 如何与TLS1.2保护的oracle服务器建立连接?

Linux 读取 - x 秒后超时*空闲*

Java - 暂停 Akka 调度程序

java - HashMap 做 containsKey 的方式不符合预期

java - 在 fragment 中创建 android 对话框而不是直接由 Activity 创建的原因是什么?

php - 为 MySQLi 查询执行设置超时

algorithm - 我如何确定所有 Actor 都收到了广播消息

java - Akka 中的轻量级线程

java - 在webapp中优雅地关闭ExecutorService?

reactjs - Axios 请求超时