本文整理汇总了Java中akka.actor.ActorSelection类的典型用法代码示例。如果您正苦于以下问题:Java ActorSelection类的具体用法?Java ActorSelection怎么用?Java ActorSelection使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ActorSelection类属于akka.actor包,在下文中一共展示了ActorSelection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: verifyActorReady
import akka.actor.ActorSelection; //导入依赖的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);
}
示例2: testExceptionOnInitialCreateTransaction
import akka.actor.ActorSelection; //导入依赖的package包/类
private void testExceptionOnInitialCreateTransaction(final Exception exToThrow, final Invoker invoker)
throws Exception {
ActorRef actorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
if (exToThrow instanceof PrimaryNotFoundException) {
doReturn(Futures.failed(exToThrow)).when(mockActorContext).findPrimaryShardAsync(anyString());
} else {
doReturn(primaryShardInfoReply(getSystem(), actorRef)).when(mockActorContext)
.findPrimaryShardAsync(anyString());
}
doReturn(Futures.failed(exToThrow)).when(mockActorContext).executeOperationAsync(
any(ActorSelection.class), any(), any(Timeout.class));
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
propagateReadFailedExceptionCause(invoker.invoke(transactionProxy));
}
示例3: initiateCaptureSnapshot
import akka.actor.ActorSelection; //导入依赖的package包/类
/**
* Initiates a snapshot capture to install on a follower.
*
* <p>
* Install Snapshot works as follows
* 1. Leader initiates the capture snapshot by calling createSnapshot on the RaftActor.
* 2. On receipt of the CaptureSnapshotReply message, the RaftActor persists the snapshot and makes a call to
* the Leader's handleMessage with a SendInstallSnapshot message.
* 3. The Leader obtains and stores the Snapshot from the SendInstallSnapshot message and sends it in chunks to
* the Follower via InstallSnapshot messages.
* 4. For each chunk, the Follower sends back an InstallSnapshotReply.
* 5. On receipt of the InstallSnapshotReply for the last chunk, the Leader marks the install complete for that
* follower.
* 6. If another follower requires a snapshot and a snapshot has been collected (via SendInstallSnapshot)
* then send the existing snapshot in chunks to the follower.
*
* @param followerId the id of the follower.
* @return true if capture was initiated, false otherwise.
*/
public boolean initiateCaptureSnapshot(final String followerId) {
FollowerLogInformation followerLogInfo = followerToLog.get(followerId);
if (snapshotHolder.isPresent()) {
// If a snapshot is present in the memory, most likely another install is in progress no need to capture
// snapshot. This could happen if another follower needs an install when one is going on.
final ActorSelection followerActor = context.getPeerActorSelection(followerId);
// Note: sendSnapshotChunk will set the LeaderInstallSnapshotState.
sendSnapshotChunk(followerActor, followerLogInfo);
return true;
}
boolean captureInitiated = context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
this.getReplicatedToAllIndex(), followerId);
if (captureInitiated) {
followerLogInfo.setLeaderInstallSnapshotState(new LeaderInstallSnapshotState(
context.getConfigParams().getSnapshotChunkSize(), logName()));
}
return captureInitiated;
}
示例4: sendInstallSnapshot
import akka.actor.ActorSelection; //导入依赖的package包/类
private void sendInstallSnapshot() {
log.debug("{}: sendInstallSnapshot", logName());
for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
String followerId = e.getKey();
ActorSelection followerActor = context.getPeerActorSelection(followerId);
FollowerLogInformation followerLogInfo = e.getValue();
if (followerActor != null) {
long nextIndex = followerLogInfo.getNextIndex();
if (followerLogInfo.getInstallSnapshotState() != null
|| context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED
|| canInstallSnapshot(nextIndex)) {
sendSnapshotChunk(followerActor, followerLogInfo);
}
}
}
}
示例5: testInitialChangeListenerEventWithContainerPath
import akka.actor.ActorSelection; //导入依赖的package包/类
@Test
public void testInitialChangeListenerEventWithContainerPath() throws DataValidationFailedException {
writeToStore(shard.getDataStore(), TEST_PATH, ImmutableNodes.containerNode(TEST_QNAME));
Entry<MockDataTreeChangeListener, ActorSelection> entry = registerChangeListener(TEST_PATH, 1);
MockDataTreeChangeListener listener = entry.getKey();
listener.waitForChangeEvents();
listener.verifyNotifiedData(TEST_PATH);
listener.reset(1);
writeToStore(shard.getDataStore(), TEST_PATH, ImmutableNodes.containerNode(TEST_QNAME));
listener.waitForChangeEvents();
listener.verifyNotifiedData(TEST_PATH);
listener.reset(1);
JavaTestKit kit = new JavaTestKit(getSystem());
entry.getValue().tell(CloseDataTreeNotificationListenerRegistration.getInstance(), kit.getRef());
kit.expectMsgClass(JavaTestKit.duration("5 seconds"), CloseDataTreeNotificationListenerRegistrationReply.class);
writeToStore(shard.getDataStore(), TEST_PATH, ImmutableNodes.containerNode(TEST_QNAME));
listener.verifyNoNotifiedData(TEST_PATH);
}
示例6: onMakeLeaderLocal
import akka.actor.ActorSelection; //导入依赖的package包/类
private void onMakeLeaderLocal() {
LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
if (isLeader()) {
getSender().tell(new Status.Success(null), getSelf());
return;
}
final ActorSelection leader = getLeader();
if (leader == null) {
// Leader is not present. The cluster is most likely trying to
// elect a leader and we should let that run its normal course
// TODO we can wait for the election to complete and retry the
// request. We can also let the caller retry by sending a flag
// in the response indicating the request is "reTryable".
getSender().tell(new Failure(
new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
+ "Currently there is no leader for " + persistenceId())),
getSelf());
return;
}
leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
}
示例7: handleReadyLocalTransaction
import akka.actor.ActorSelection; //导入依赖的package包/类
@SuppressWarnings("checkstyle:IllegalCatch")
private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
boolean isLeaderActive = isLeaderActive();
if (isLeader() && isLeaderActive) {
try {
commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
} catch (Exception e) {
LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
message.getTransactionId(), e);
getSender().tell(new Failure(e), getSelf());
}
} else {
ActorSelection leader = getLeader();
if (!isLeaderActive || leader == null) {
messageRetrySupport.addMessageToRetry(message, getSender(),
"Could not process ready local transaction " + message.getTransactionId());
} else {
LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
leader.forward(message, getContext());
}
}
}
示例8: handleForwardedReadyTransaction
import akka.actor.ActorSelection; //导入依赖的package包/类
private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
boolean isLeaderActive = isLeaderActive();
if (isLeader() && isLeaderActive) {
commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
} else {
ActorSelection leader = getLeader();
if (!isLeaderActive || leader == null) {
messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
"Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
} else {
LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
leader.forward(readyLocal, getContext());
}
}
}
示例9: processListenerRegistrationMessage
import akka.actor.ActorSelection; //导入依赖的package包/类
protected ActorSelection processListenerRegistrationMessage(M message) {
final ActorSelection listenerActor = selectActor(message.getListenerActorPath());
// We have a leader so enable the listener.
listenerActor.tell(new EnableNotification(true, persistenceId()), getSelf());
if (!message.isRegisterOnAllInstances()) {
// This is a leader-only registration so store a reference to the listener actor so it can be notified
// at a later point if notifications should be enabled or disabled.
leaderOnlyListenerActors.add(listenerActor);
}
allListenerActors.add(listenerActor);
return listenerActor;
}
示例10: setListenerRegistrationActor
import akka.actor.ActorSelection; //导入依赖的package包/类
private void setListenerRegistrationActor(final ActorSelection actor) {
if (actor == null) {
LOG.debug("{}: Ignoring null actor on {}", logContext(), this);
return;
}
synchronized (this) {
if (!isClosed()) {
this.listenerRegistrationActor = actor;
return;
}
}
// This registration has already been closed, notify the actor
actor.tell(CloseDataTreeNotificationListenerRegistration.getInstance(), null);
}
示例11: initiateCoordinatedCommit
import akka.actor.ActorSelection; //导入依赖的package包/类
Future<ActorSelection> initiateCoordinatedCommit() {
final Future<Object> messageFuture = initiateCommit(false);
final Future<ActorSelection> ret = TransactionReadyReplyMapper.transform(messageFuture, actorContext,
transaction.getIdentifier());
ret.onComplete(new OnComplete<ActorSelection>() {
@Override
public void onComplete(final Throwable failure, final ActorSelection success) throws Throwable {
if (failure != null) {
LOG.info("Failed to prepare transaction {} on backend", transaction.getIdentifier(), failure);
transactionAborted(transaction);
return;
}
LOG.debug("Transaction {} resolved to actor {}", transaction.getIdentifier(), success);
}
}, actorContext.getClientDispatcher());
return ret;
}
示例12: tryCommitModifications
import akka.actor.ActorSelection; //导入依赖的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());
}
}
}
示例13: possiblyRemoveAllInitialCandidates
import akka.actor.ActorSelection; //导入依赖的package包/类
void possiblyRemoveAllInitialCandidates(final ActorSelection leader) {
// The following handles removing all candidates on startup when re-joining with a remote leader. When a
// follower is detected as down, the leader will re-assign new owners to entities that were owned by the
// down member but doesn't remove the down member as a candidate, as the down node may actually be isolated
// and still running. Therefore on startup we send an initial message to the remote leader to remove any
// potential stale candidates we had previously registered, as it's possible a candidate may not be
// registered by a client in the new incarnation. We have to send the RemoveAllCandidates message prior to any
// pending registrations.
if (removeAllInitialCandidates && leader != null) {
removeAllInitialCandidates = false;
if (!isLeader()) {
LOG.debug("{} - got new leader {} on startup - sending RemoveAllCandidates", persistenceId(), leader);
leader.tell(new RemoveAllCandidates(localMemberName), ActorRef.noSender());
}
}
}
示例14: testExecuteRemoteOperationAsync
import akka.actor.ActorSelection; //导入依赖的package包/类
@Test
@SuppressWarnings("checkstyle:IllegalCatch")
public void testExecuteRemoteOperationAsync() {
new JavaTestKit(getSystem()) {
{
ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
ActorRef shardManagerActorRef = getSystem().actorOf(MockShardManager.props(true, shardActorRef));
ActorContext actorContext = new ActorContext(getSystem(), shardManagerActorRef,
mock(ClusterWrapper.class), mock(Configuration.class));
ActorSelection actor = actorContext.actorSelection(shardActorRef.path());
Future<Object> future = actorContext.executeOperationAsync(actor, "hello");
try {
Object result = Await.result(future, Duration.create(3, TimeUnit.SECONDS));
assertEquals("Result", "hello", result);
} catch (Exception e) {
throw new AssertionError(e);
}
}
};
}
示例15: setPrimaryShard
import akka.actor.ActorSelection; //导入依赖的package包/类
/**
* Sets the target primary shard and initiates a CreateTransaction try.
*/
void setPrimaryShard(PrimaryShardInfo primaryShardInfo) {
this.primaryShardInfo = primaryShardInfo;
if (getTransactionType() == TransactionType.WRITE_ONLY
&& getActorContext().getDatastoreContext().isWriteOnlyTransactionOptimizationsEnabled()) {
ActorSelection primaryShard = primaryShardInfo.getPrimaryShardActor();
LOG.debug("Tx {} Primary shard {} found - creating WRITE_ONLY transaction context",
getIdentifier(), primaryShard);
// For write-only Tx's we prepare the transaction modifications directly on the shard actor
// to avoid the overhead of creating a separate transaction actor.
transactionContextWrapper.executePriorTransactionOperations(createValidTransactionContext(
primaryShard, String.valueOf(primaryShard.path()), primaryShardInfo.getPrimaryShardVersion()));
} else {
tryCreateTransaction();
}
}