Akka的actor中,可以设置receiveTimeout,一度为该设置项比较疑惑。
receive time out是指最多允许多长时间,该actor无消息接口,即空闲,否则会超时的消息通知。
该Actor一个典型的应用即心跳Actor,在规则时间内无心跳信息,则超时,进入超时处理。
示例:
package com.zte.sunquan.demo.actor.recvtimeout;
import akka.actor.AbstractActor;
import akka.actor.Props;
import akka.actor.ReceiveTimeout;
import java.util.concurrent.TimeUnit;
/**
* Created by on 2017/10/10.
*/
public class ProcessReceiveTOActor extends AbstractActor {
//receive time out是指最多允许多长时间 该actor无消息接收,即空闲
public ProcessReceiveTOActor() {
getContext().setReceiveTimeout(scala.concurrent.duration.Duration.apply(10, TimeUnit.SECONDS));
}
public static Props props() {
return Props.create(ProcessReceiveTOActor.class);
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(String.class, "Hello,world"::equals, s -> {
getSender().tell("get message " + s, getSelf());
})
.match(ReceiveTimeout.class, p -> {
System.out.println("receive time out.+Instant.now()"
);
// getContext().setReceiveTimeout(Duration.Undefined());
// throw new RuntimeException("received timeout");
})
.build();
}
}
测试用例:
package com.zte.sunquan.demo.actor.recvtimeout;
import akka.actor.ActorSystem;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
/**
* Created by on 2017/9/22.
*/
public class ProcessReceiveTOActorTest {
@Test
public void startTest() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
ActorSystem system = ActorSystem.create();
system.actorOf(ProcessReceiveTOActor.props());
latch.await();
}
}
打印:
get message Hello,world:2017-10-16T02:07:26.680Z
receive time out.2017-10-16T02:07:36.690Z //10秒后无消息接收,则超时
receive time out.2017-10-16T02:07:46.711Z