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


Java Patterns.gracefulStop方法代碼示例

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


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

示例1: sendShutDown

import akka.pattern.Patterns; //導入方法依賴的package包/類
private void sendShutDown(final ActorRef actor) throws Exception {
    testLog.info("sendShutDown for {} starting", actor.path());

    FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
    Future<Boolean> stopFuture = Patterns.gracefulStop(actor, duration, Shutdown.INSTANCE);

    Boolean stopped = Await.result(stopFuture, duration);
    assertEquals("Stopped", Boolean.TRUE, stopped);

    testLog.info("sendShutDown for {} ending", actor.path());
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:12,代碼來源:LeadershipTransferIntegrationTest.java

示例2: sendShutDownToLeaderAndVerifyLeadershipTransferToFollower1

import akka.pattern.Patterns; //導入方法依賴的package包/類
private void sendShutDownToLeaderAndVerifyLeadershipTransferToFollower1() throws Exception {
    testLog.info("sendShutDownToLeaderAndVerifyLeadershipTransferToFollower1 starting");

    clearMessages(leaderNotifierActor);
    clearMessages(follower1NotifierActor);
    clearMessages(follower2NotifierActor);
    clearMessages(follower3NotifierActor);

    // Simulate a delay for follower2 in receiving the LeaderTransitioning message with null leader id.
    final TestRaftActor follower2Instance = follower2Actor.underlyingActor();
    follower2Instance.startDropMessages(LeaderTransitioning.class);

    FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
    final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);

    verifyRaftState(follower1Actor, RaftState.Leader);

    Boolean stopped = Await.result(stopFuture, duration);
    assertEquals("Stopped", Boolean.TRUE, stopped);

    // Re-enable LeaderTransitioning messages to follower2.
    final LeaderTransitioning leaderTransitioning = expectFirstMatching(follower2CollectorActor,
            LeaderTransitioning.class);
    follower2Instance.stopDropMessages(LeaderTransitioning.class);

    follower2Instance.stopDropMessages(AppendEntries.class);
    ApplyState applyState = expectFirstMatching(follower2CollectorActor, ApplyState.class);
    assertEquals("Apply sate index", 0, applyState.getReplicatedLogEntry().getIndex());

    // Now send the LeaderTransitioning to follower2 after it has received AppendEntries from the new leader.
    follower2Actor.tell(leaderTransitioning, ActorRef.noSender());

    verifyLeaderStateChangedMessages(leaderNotifierActor, null, follower1Id);
    verifyLeaderStateChangedMessages(follower1NotifierActor, null, follower1Id);
    // follower2 should only get 1 LeaderStateChanged with the new leaderId - the LeaderTransitioning message
    // should not generate a LeaderStateChanged with null leaderId since it arrived after the new leaderId was set.
    verifyLeaderStateChangedMessages(follower2NotifierActor, follower1Id);
    verifyLeaderStateChangedMessages(follower3NotifierActor, null, follower1Id);

    testLog.info("sendShutDownToLeaderAndVerifyLeadershipTransferToFollower1 ending");
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:42,代碼來源:LeadershipTransferIntegrationTest.java

示例3: removeShard

import akka.pattern.Patterns; //導入方法依賴的package包/類
@SuppressWarnings("checkstyle:IllegalCatch")
private void removeShard(final ShardIdentifier shardId) {
    final String shardName = shardId.getShardName();
    final ShardInformation shardInformation = localShards.remove(shardName);
    if (shardInformation == null) {
        LOG.debug("{} : Shard replica {} is not present in list", persistenceId(), shardId.toString());
        return;
    }

    final ActorRef shardActor = shardInformation.getActor();
    if (shardActor != null) {
        long timeoutInMS = Math.max(shardInformation.getDatastoreContext().getShardRaftConfig()
                .getElectionTimeOutInterval().$times(3).toMillis(), 10000);

        LOG.debug("{} : Sending Shutdown to Shard actor {} with {} ms timeout", persistenceId(), shardActor,
                timeoutInMS);

        final Future<Boolean> stopFuture = Patterns.gracefulStop(shardActor,
                FiniteDuration.apply(timeoutInMS, TimeUnit.MILLISECONDS), Shutdown.INSTANCE);

        final CompositeOnComplete<Boolean> onComplete = new CompositeOnComplete<Boolean>() {
            @Override
            public void onComplete(final Throwable failure, final Boolean result) {
                if (failure == null) {
                    LOG.debug("{} : Successfully shut down Shard actor {}", persistenceId(), shardActor);
                } else {
                    LOG.warn("{}: Failed to shut down Shard actor {}", persistenceId(), shardActor, failure);
                }

                self().tell((RunnableMessage) () -> {
                    // At any rate, invalidate primaryShardInfo cache
                    primaryShardInfoCache.remove(shardName);

                    shardActorsStopping.remove(shardName);
                    notifyOnCompleteTasks(failure, result);
                }, ActorRef.noSender());
            }
        };

        shardActorsStopping.put(shardName, onComplete);
        stopFuture.onComplete(onComplete, new Dispatchers(context().system().dispatchers())
                .getDispatcher(Dispatchers.DispatcherType.Client));
    }

    LOG.debug("{} : Local Shard replica for shard {} has been removed", persistenceId(), shardName);
    persistShardList();
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:48,代碼來源:ShardManager.java

示例4: testLeadershipTransferOnShutdown

import akka.pattern.Patterns; //導入方法依賴的package包/類
@Test
public void testLeadershipTransferOnShutdown() throws Exception {
    //TODO remove when test passes also for ClientBackedDataStore
    Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
    leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
    followerDatastoreContextBuilder.shardElectionTimeoutFactor(10).customRaftPolicyImplementation(null);
    final String testName = "testLeadershipTransferOnShutdown";
    initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS_AND_PEOPLE);

    final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
            DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(100),
            commitTimeout);
    try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
            testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {

        followerTestKit.waitForMembersUp("member-3");
        follower2TestKit.waitForMembersUp("member-1", "member-2");

        // Create and submit a couple tx's so they're pending.

        DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
        writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
        writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
        writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
        final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();

        IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
            stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));

        writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
        final MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
        writeTx.write(CarsModel.newCarPath("optima"), car);
        final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();

        IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
            stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));

        // Gracefully stop the leader via a Shutdown message.

        sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
            .shardElectionTimeoutFactor(100));

        final FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
        final Future<ActorRef> future = leaderDistributedDataStore.getActorContext().findLocalShardAsync("cars");
        final ActorRef leaderActor = Await.result(future, duration);

        final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);

        // Commit the 2 transactions. They should finish and succeed.

        followerTestKit.doCommit(cohort1);
        followerTestKit.doCommit(cohort2);

        // Wait for the leader actor stopped.

        final Boolean stopped = Await.result(stopFuture, duration);
        assertEquals("Stopped", Boolean.TRUE, stopped);

        // Verify leadership was transferred by reading the committed data from the other nodes.

        verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
        verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
    }
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:65,代碼來源:DistributedDataStoreRemotingIntegrationTest.java

示例5: testShutDown

import akka.pattern.Patterns; //導入方法依賴的package包/類
@Test
public void testShutDown() throws Exception {
    LOG.info("testShutDown starting");
    new JavaTestKit(getSystem()) {
        {
            MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
                    .put("shard1", Arrays.asList("member-1")).put("shard2", Arrays.asList("member-1")).build());

            String shardId1 = ShardIdentifier.create("shard1", MEMBER_1, shardMrgIDSuffix).toString();
            ActorRef shard1 = actorFactory.createActor(MessageCollectorActor.props(), shardId1);

            String shardId2 = ShardIdentifier.create("shard2", MEMBER_1, shardMrgIDSuffix).toString();
            ActorRef shard2 = actorFactory.createActor(MessageCollectorActor.props(), shardId2);

            ActorRef shardManager = actorFactory.createActor(newTestShardMgrBuilder(mockConfig)
                    .addShardActor("shard1", shard1).addShardActor("shard2", shard2).props());

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

            FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
            Future<Boolean> stopFuture = Patterns.gracefulStop(shardManager, duration, Shutdown.INSTANCE);

            MessageCollectorActor.expectFirstMatching(shard1, Shutdown.class);
            MessageCollectorActor.expectFirstMatching(shard2, Shutdown.class);

            try {
                Await.ready(stopFuture, FiniteDuration.create(500, TimeUnit.MILLISECONDS));
                fail("ShardManager actor stopped without waiting for the Shards to be stopped");
            } catch (TimeoutException e) {
                // expected
            }

            actorFactory.killActor(shard1, this);
            actorFactory.killActor(shard2, this);

            Boolean stopped = Await.result(stopFuture, duration);
            assertEquals("Stopped", Boolean.TRUE, stopped);
        }
    };

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

示例6: shutdown

import akka.pattern.Patterns; //導入方法依賴的package包/類
/**
 * Shuts down this registry and the associated {@link MetricReporter}.
 */
public void shutdown() {
	synchronized (lock) {
		Future<Boolean> stopFuture = null;
		FiniteDuration stopTimeout = null;

		if (queryService != null) {
			stopTimeout = new FiniteDuration(1L, TimeUnit.SECONDS);

			try {
				stopFuture = Patterns.gracefulStop(queryService, stopTimeout);
			} catch (IllegalStateException ignored) {
				// this can happen if the underlying actor system has been stopped before shutting
				// the metric registry down
				// TODO: Pull the MetricQueryService actor out of the MetricRegistry
				LOG.debug("The metric query service actor has already been stopped because the " +
					"underlying ActorSystem has already been shut down.");
			}
		}

		if (reporters != null) {
			for (MetricReporter reporter : reporters) {
				try {
					reporter.close();
				} catch (Throwable t) {
					LOG.warn("Metrics reporter did not shut down cleanly", t);
				}
			}
			reporters = null;
		}
		shutdownExecutor();

		if (stopFuture != null) {
			boolean stopped = false;

			try {
				stopped = Await.result(stopFuture, stopTimeout);
			} catch (Exception e) {
				LOG.warn("Query actor did not properly stop.", e);
			}

			if (!stopped) {
				// the query actor did not stop in time, let's kill him
				queryService.tell(Kill.getInstance(), ActorRef.noSender());
			}
		}
	}
}
 
開發者ID:axbaretto,項目名稱:flink,代碼行數:51,代碼來源:MetricRegistryImpl.java


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