當前位置: 首頁>>代碼示例>>Java>>正文


Java Patterns.ask方法代碼示例

本文整理匯總了Java中akka.pattern.Patterns.ask方法的典型用法代碼示例。如果您正苦於以下問題:Java Patterns.ask方法的具體用法?Java Patterns.ask怎麽用?Java Patterns.ask使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在akka.pattern.Patterns的用法示例。


在下文中一共展示了Patterns.ask方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: verifyActorReady

import akka.pattern.Patterns; //導入方法依賴的package包/類
@SuppressWarnings("checkstyle:IllegalCatch")
private void verifyActorReady(ActorRef actorRef) {
    // Sometimes we see messages go to dead letters soon after creation - it seems the actor isn't quite
    // in a state yet to receive messages or isn't actually created yet. This seems to happen with
    // actorSelection so, to alleviate it, we use an actorSelection and send an Identify message with
    // retries to ensure it's ready.

    Timeout timeout = new Timeout(100, TimeUnit.MILLISECONDS);
    Throwable lastError = null;
    Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
        try {
            ActorSelection actorSelection = system.actorSelection(actorRef.path().toString());
            Future<Object> future = Patterns.ask(actorSelection, new Identify(""), timeout);
            ActorIdentity reply = (ActorIdentity)Await.result(future, timeout.duration());
            Assert.assertNotNull("Identify returned null", reply.getRef());
            return;
        } catch (Exception | AssertionError e) {
            Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
            lastError = e;
        }
    }

    throw new RuntimeException(lastError);
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:26,代碼來源:TestActorFactory.java

示例2: testPersistentActorWIthIgnite

import akka.pattern.Patterns; //導入方法依賴的package包/類
@Test
public void testPersistentActorWIthIgnite() throws Exception {
    ActorRef actorRef = actorSystem.actorOf(Props.create(IgnitePersistentTestActor.class, "1"));
    actorRef.tell("+a", ActorRef.noSender());
    actorRef.tell("+b", ActorRef.noSender());
    actorRef.tell("+c", ActorRef.noSender());
    actorRef.tell("throw", ActorRef.noSender());

    Future<Object> future = Patterns.ask(actorRef, "-b", 1000);
    Await.result(future, Duration.create(1, TimeUnit.SECONDS));

    IgniteCache<Object, Object> cache = ignite.getOrCreateCache("akka-journal");
    Assert.assertEquals(cache.size(), 4);

    actorSystem.actorSelection("akka://test/user/**").tell("!!!", ActorRef.noSender());

    Await.result(actorSystem.terminate(), Duration.create(1, TimeUnit.SECONDS));
}
 
開發者ID:Romeh,項目名稱:akka-persistance-ignite,代碼行數:19,代碼來源:IgniteJournalCacheTest.java

示例3: verifyRaftState

import akka.pattern.Patterns; //導入方法依賴的package包/類
static void verifyRaftState(final TestActorRef<? extends EntityOwnershipShard> shard,
        Consumer<OnDemandRaftState> verifier)
        throws Exception {
    AssertionError lastError = null;
    Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
        FiniteDuration operationDuration = Duration.create(5, TimeUnit.SECONDS);
        Future<Object> future = Patterns.ask(shard, GetOnDemandRaftState.INSTANCE, new Timeout(operationDuration));
        OnDemandRaftState raftState = (OnDemandRaftState)Await.result(future, operationDuration);
        try {
            verifier.accept(raftState);
            return;
        } catch (AssertionError e) {
            lastError = e;
            Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
        }
    }

    throw lastError;
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:21,代碼來源:AbstractEntityOwnershipTest.java

示例4: testTimeToBlink

import akka.pattern.Patterns; //導入方法依賴的package包/類
@Test
public void testTimeToBlink() throws Exception {

    new JavaTestKit(system) {{

        List<SimonColorImpl> colors = getExampleSequence();
        TimeToBlinkMsg msg = new TimeToBlinkMsg(colors);
        Future<Object> future = Patterns.ask(ac.getGameViewActorRef(), msg, 3000);
        assertTrue(future.isCompleted());

        TestMessage received = (TestMessage)Await.result(future, Duration.Zero());
        assertEquals(MessageType.TEST, received.getType());

        assertTrue(ac.getGameViewActor().getCpuColorIndex() == 0);
        assertFalse(ac.getGameViewActor().isPaused());
        assertFalse(ac.getGameViewActor().isPlayerTurn());
        assertTrue(ac.getGameViewActor().getCpuSequence().equals(colors));

    }};
}
 
開發者ID:simoneapp,項目名稱:S3-16-simone,代碼行數:21,代碼來源:SinglePlayerTest.java

示例5: testHandlePlayerMsg

import akka.pattern.Patterns; //導入方法依賴的package包/類
@Test
public void testHandlePlayerMsg() throws Exception {

    new JavaTestKit(system) {{

        PlayerTurnMsg msg = new PlayerTurnMsg();
        Future<Object> future = Patterns.ask(ac.getGameViewActorRef(), msg, 3000);
        assertTrue(future.isCompleted());

        TestMessage received = (TestMessage)Await.result(future, Duration.Zero());
        assertEquals(MessageType.TEST, received.getType());

        assertEquals(ac.getGameViewActor().getPlayerColorIndex(), 0);
        assertEquals(ac.getGameViewActor().getPlayerSequence().size(), 0);
    }};
}
 
開發者ID:simoneapp,項目名稱:S3-16-simone,代碼行數:17,代碼來源:SinglePlayerTest.java

示例6: testPause

import akka.pattern.Patterns; //導入方法依賴的package包/類
@Test
public void testPause() throws Exception {

    new JavaTestKit(system) {{

        PauseMsg pause1 = new PauseMsg(true);
        Future<Object> future1 = Patterns.ask(ac.getGameViewActorRef(), pause1, 3000);
        assertTrue(future1.isCompleted());
        Await.result(future1, Duration.Zero());

        assertTrue(ac.getGameViewActor().isPaused());

        PauseMsg pause2 = new PauseMsg(false);
        Future<Object> future2 = Patterns.ask(ac.getGameViewActorRef(), pause2, 3000);
        assertTrue(future2.isCompleted());
        Await.result(future2, Duration.Zero());

        assertFalse(ac.getGameViewActor().isPaused());

        TestMessage received3 = (TestMessage)Await.result(future2, Duration.Zero());
        assertEquals(MessageType.TEST, received3.getType());
        assertFalse(ac.getGameViewActor().isPaused());
    }};
}
 
開發者ID:simoneapp,項目名稱:S3-16-simone,代碼行數:25,代碼來源:SinglePlayerTest.java

示例7: waitUntilLeader

import akka.pattern.Patterns; //導入方法依賴的package包/類
@SuppressWarnings("checkstyle:IllegalCatch")
public static void waitUntilLeader(ActorRef actorRef) {
    FiniteDuration duration = Duration.create(100, TimeUnit.MILLISECONDS);
    for (int i = 0; i < 20 * 5; i++) {
        Future<Object> future = Patterns.ask(actorRef, FindLeader.INSTANCE, new Timeout(duration));
        try {
            final Optional<String> maybeLeader = ((FindLeaderReply)Await.result(future, duration)).getLeaderActor();
            if (maybeLeader.isPresent()) {
                return;
            }
        } catch (Exception e) {
            LOG.error("FindLeader failed", e);
        }

        Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
    }

    Assert.fail("Leader not found for actorRef " + actorRef.path());
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:20,代碼來源:RaftActorTestKit.java

示例8: tryCommitModifications

import akka.pattern.Patterns; //導入方法依賴的package包/類
void tryCommitModifications(final BatchedModifications modifications) {
    if (isLeader()) {
        LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(),
                modifications.getTransactionId());

        // Note that it's possible the commit won't get consensus and will timeout and not be applied
        // to the state. However we don't need to retry it in that case b/c it will be committed to
        // the journal first and, once a majority of followers come back on line and it is replicated,
        // it will be applied at that point.
        handleBatchedModificationsLocal(modifications, self());
    } else {
        final ActorSelection leader = getLeader();
        if (leader != null) {
            possiblyRemoveAllInitialCandidates(leader);

            LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
                    modifications.getTransactionId(), leader);

            Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
                    getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));

            Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
        }
    }
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:26,代碼來源:EntityOwnershipShard.java

示例9: performRegistration

import akka.pattern.Patterns; //導入方法依賴的package包/類
private synchronized void performRegistration(ActorRef shard) {
    if (isClosed()) {
        return;
    }
    cohortRegistry = shard;
    Future<Object> future =
            Patterns.ask(shard, new DataTreeCohortActorRegistry.RegisterCohort(subtree, actor), TIMEOUT);
    future.onComplete(new OnComplete<Object>() {

        @Override
        public void onComplete(Throwable failure, Object val) {
            if (failure != null) {
                LOG.error("Unable to register {} as commit cohort", getInstance(), failure);
            }
            if (isClosed()) {
                removeRegistration();
            }
        }

    }, actorContext.getClientDispatcher());
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:22,代碼來源:DataTreeCohortRegistrationProxy.java

示例10: testOnReceiveFindLocalShardWaitForShardInitialized

import akka.pattern.Patterns; //導入方法依賴的package包/類
@Test
public void testOnReceiveFindLocalShardWaitForShardInitialized() throws Exception {
    LOG.info("testOnReceiveFindLocalShardWaitForShardInitialized starting");
    new JavaTestKit(getSystem()) {
        {
            final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());

            shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());

            // We're passing waitUntilInitialized = true to FindLocalShard
            // so the response should be
            // delayed until we send ActorInitialized.
            Future<Object> future = Patterns.ask(shardManager, new FindLocalShard(Shard.DEFAULT_NAME, true),
                    new Timeout(5, TimeUnit.SECONDS));

            shardManager.tell(new ActorInitialized(), mockShardActor);

            Object resp = Await.result(future, duration("5 seconds"));
            assertTrue("Expected: LocalShardFound, Actual: " + resp, resp instanceof LocalShardFound);
        }
    };

    LOG.info("testOnReceiveFindLocalShardWaitForShardInitialized starting");
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:25,代碼來源:ShardManagerTest.java

示例11: akkaFuture

import akka.pattern.Patterns; //導入方法依賴的package包/類
/**
 * 訪問路徑: http://localhost:8080/akka/future
 *
 * @param request
 * @param response
 * @param model
 * @return
 */
@RequestMapping(value = "/akka/future", method = RequestMethod.GET)
public void akkaFuture(HttpServletRequest request, HttpServletResponse response, Model model){
    int a = 1;

    try {
        ActorRef actorRef1 = actorGenerator.createUniqueActor("printerActor", "printerActorName");
        PrinterMsg printerMsg = new PrinterMsg(99, "hello world.");

        Timeout timeout = new Timeout(Duration.create(10, TimeUnit.SECONDS));
        Future<Object> future = Patterns.ask(actorRef1, "hello world", timeout);
        Object result = Await.result(future, Duration.create(10, TimeUnit.SECONDS));


        int c = 3;

    } catch (Exception e) {
        logger.error("akka exception:", e);
    }

    int b = 2;
}
 
開發者ID:packease,項目名稱:packease-framework-java,代碼行數:30,代碼來源:DemoController.java

示例12: channelsRegistry

import akka.pattern.Patterns; //導入方法依賴的package包/類
@Bean
public ChannelsRegistry channelsRegistry() {
    ChannelsActors channelsActors = channelsActors();
    return tempo -> {
        Future<Object> result = Patterns.ask(channelsActors.get(tempo), ListChannels.instance(), 1000);
        CompletionStage<Object> stage = FutureConverters.toJava(result);
        return stage.thenCompose(o -> {
            if (o instanceof Channels) {
                return CompletableFuture.completedFuture(((Channels) o).getChannels());
            }
            else {
                CompletableFuture<List<Channel>> f = new CompletableFuture<>();
                f.completeExceptionally(new IllegalStateException());
                return f;
            }
        });
    };
}
 
開發者ID:nosceon,項目名稱:tenorite,代碼行數:19,代碼來源:ChannelsConfig.java

示例13: testLeaderElection

import akka.pattern.Patterns; //導入方法依賴的package包/類
/**
 * Tests that a single JobManager is elected as the leader by ZooKeeper.
 */
@Test
public void testLeaderElection() throws Exception {
	final Configuration configuration = ZooKeeperTestUtils
		.createZooKeeperHAConfig(
			testingServer.getConnectString(),
			tempFolder.getRoot().getPath());

	ActorRef jm = null;

	try {
		Props jmProps = createJobManagerProps(configuration);

		jm = actorSystem.actorOf(jmProps);

		Future<Object> leaderFuture = Patterns.ask(
				jm,
				TestingJobManagerMessages.getNotifyWhenLeader(),
				timeout);

		Await.ready(leaderFuture, duration);
	} finally {
		TestingUtils.stopActor(jm);
	}

}
 
開發者ID:axbaretto,項目名稱:flink,代碼行數:29,代碼來源:JobManagerLeaderElectionTest.java

示例14: testConnectionTimeoutWithoutJobManagerForSubmission

import akka.pattern.Patterns; //導入方法依賴的package包/類
/** Tests that a {@link JobClientActorConnectionTimeoutException}
 * is thrown when the JobSubmissionClientActor wants to submit a job but has not connected to a JobManager.
 *
 * @throws Exception
 */
@Test(expected=JobClientActorConnectionTimeoutException.class)
public void testConnectionTimeoutWithoutJobManagerForSubmission() throws Exception {
	FiniteDuration jobClientActorTimeout = new FiniteDuration(1L, TimeUnit.SECONDS);
	FiniteDuration timeout = jobClientActorTimeout.$times(2);

	TestingLeaderRetrievalService testingLeaderRetrievalService = new TestingLeaderRetrievalService(
		"localhost",
		HighAvailabilityServices.DEFAULT_LEADER_ID);

	Props jobClientActorProps = JobSubmissionClientActor.createActorProps(
		testingLeaderRetrievalService,
		jobClientActorTimeout,
		false,
		clientConfig);

	ActorRef jobClientActor = system.actorOf(jobClientActorProps);

	Future<Object> jobExecutionResult = Patterns.ask(
		jobClientActor,
		new JobClientMessages.SubmitJobAndWait(testJobGraph),
		new Timeout(timeout));

	Await.result(jobExecutionResult, timeout);
}
 
開發者ID:axbaretto,項目名稱:flink,代碼行數:30,代碼來源:JobClientActorTest.java

示例15: testConnectionTimeoutWithoutJobManagerForRegistration

import akka.pattern.Patterns; //導入方法依賴的package包/類
/** Tests that a {@link JobClientActorConnectionTimeoutException}
 * is thrown when the JobAttachmentClientActor attach to a job at the JobManager
 * but has not connected to a JobManager.
 */
@Test(expected=JobClientActorConnectionTimeoutException.class)
public void testConnectionTimeoutWithoutJobManagerForRegistration() throws Exception {
	FiniteDuration jobClientActorTimeout = new FiniteDuration(1L, TimeUnit.SECONDS);
	FiniteDuration timeout = jobClientActorTimeout.$times(2);

	TestingLeaderRetrievalService testingLeaderRetrievalService = new TestingLeaderRetrievalService(
		"localhost",
		HighAvailabilityServices.DEFAULT_LEADER_ID);

	Props jobClientActorProps = JobAttachmentClientActor.createActorProps(
		testingLeaderRetrievalService,
		jobClientActorTimeout,
		false);

	ActorRef jobClientActor = system.actorOf(jobClientActorProps);

	Future<Object> jobExecutionResult = Patterns.ask(
		jobClientActor,
		new JobClientMessages.AttachToJobAndWait(testJobGraph.getJobID()),
		new Timeout(timeout));

	Await.result(jobExecutionResult, timeout);
}
 
開發者ID:axbaretto,項目名稱:flink,代碼行數:28,代碼來源:JobClientActorTest.java


注:本文中的akka.pattern.Patterns.ask方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。