Actor receive timeout

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值