akka.actor.ActorSelection Java Examples
The following examples show how to use
akka.actor.ActorSelection.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BaseActor.java From sunbird-lms-service with MIT License | 6 votes |
protected ActorRef getActorRef(String operation) { int waitTime = 10; ActorSelection select = null; ActorRef actor = RequestRouter.getActor(operation); if (null != actor) { return actor; } else { select = (BaseMWService.getRemoteRouter(RequestRouter.class.getSimpleName()) == null ? (BaseMWService.getRemoteRouter(BackgroundRequestRouter.class.getSimpleName())) : BaseMWService.getRemoteRouter(RequestRouter.class.getSimpleName())); CompletionStage<ActorRef> futureActor = select.resolveOneCS(Duration.create(waitTime, "seconds")); try { actor = futureActor.toCompletableFuture().get(); } catch (Exception e) { ProjectLogger.log( "InterServiceCommunicationImpl : getResponse - unable to get actorref from actorselection " + e.getMessage(), e); } return actor; } }
Example #2
Source File: SshClusterManagerImpl.java From java-11-examples with Apache License 2.0 | 6 votes |
public void onSessionCloseResponse(SessionCloseResponse sessionCloseResponse) { if (isLeader.get()) { LOG.info("session close response: {}", sessionCloseResponse.getSessionId()); SessionCloseRequest sessionCloseRequest = pendingCloseSessionRequests.remove(sessionCloseResponse.getClientId()); if (sessionCloseRequest != null) { for (MemberInfo memberInfo : members.values()) { if (sessionCloseRequest.getSessionActorAddress().startsWith(memberInfo.getMemberAddress())) { memberInfo.removeSessionBySessionId(sessionCloseResponse.getSessionId()); break; } } ActorSelection actorSelection = actorSystem.actorSelection(sessionCloseResponse.getClientActorAddress()); actorSelection.tell(sessionCloseResponse, selfRef); } } }
Example #3
Source File: ArticleParseClusterClient.java From learning-akka with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { Timeout timeout = new Timeout(Duration.create(5, "seconds")); ActorSystem system = ActorSystem.create("clientSystem"); Set<ActorSelection> initialContacts = new HashSet<ActorSelection>(); initialContacts.add(system.actorSelection("akka.tcp://[email protected]:2552/user/receptionist")); initialContacts.add(system.actorSelection("akka.tcp://[email protected]:2551/user/receptionist")); ActorRef receptionist = system.actorOf(ClusterClient.defaultProps(initialContacts)); ClusterClient.Send msg = new ClusterClient.Send("/user/workers", articleToParse, false); Future f = Patterns.ask(receptionist, msg, timeout); String result = (String) Await.result(f, timeout.duration()); System.out.println("result: " + result); }
Example #4
Source File: Slave.java From akka-tutorial with Apache License 2.0 | 6 votes |
private void handle(AddressMessage message) { // Cancel any running connect schedule, because got a new address if (this.connectSchedule != null) { this.connectSchedule.cancel(); this.connectSchedule = null; } // Find the shepherd actor in the remote actor system final ActorSelection selection = this.getContext().getSystem().actorSelection(String.format("%s/user/%s", message.address, Shepherd.DEFAULT_NAME)); // Register the local actor system by periodically sending subscription messages (until an acknowledgement was received) final Scheduler scheduler = this.getContext().getSystem().scheduler(); final ExecutionContextExecutor dispatcher = this.getContext().getSystem().dispatcher(); this.connectSchedule = scheduler.schedule( Duration.Zero(), Duration.create(5, TimeUnit.SECONDS), () -> selection.tell(new Shepherd.SubscriptionMessage(), this.getSelf()), dispatcher ); }
Example #5
Source File: AcknowledgementForwarderActorTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void createAcknowledgementForwarderAndThreadAcknowledgementThrough() throws ExecutionException, InterruptedException { final AcknowledgementLabel acknowledgementLabel = AcknowledgementLabel.of("my-requested-ack"); final DittoHeaders dittoHeaders = DittoHeaders.newBuilder() .randomCorrelationId() .acknowledgementRequest(AcknowledgementRequest.of(acknowledgementLabel)) .build(); final ThingId entityId = ThingId.generateRandom(); final Acknowledgement acknowledgement = Acknowledgement.of(acknowledgementLabel, entityId, HttpStatusCode.ACCEPTED, dittoHeaders); new TestKit(actorSystem) {{ when(actorContext.sender()).thenReturn(getRef()); final Optional<ActorRef> underTest = AcknowledgementForwarderActor.startAcknowledgementForwarder(actorContext, entityId, dittoHeaders, acknowledgementConfig); softly.assertThat(underTest).isPresent(); final ActorSelection ackForwarderSelection = actorSystem.actorSelection( "/user/" + AcknowledgementForwarderActor.determineActorName(dittoHeaders)); softly.assertThat(underTest.get()).isEqualByComparingTo( ackForwarderSelection.resolveOne(Duration.ofMillis(100)).toCompletableFuture().get()); ackForwarderSelection.tell(acknowledgement, getRef()); expectMsg(acknowledgement); }}; }
Example #6
Source File: BaseMWService.java From sunbird-lms-service with MIT License | 5 votes |
public static ActorSelection getRemoteRouter(String router) { String path = null; if (BackgroundRequestRouter.class.getSimpleName().equals(router)) { path = config.getString("sunbird_remote_bg_req_router_path"); return system.actorSelection(path); } else if (RequestRouter.class.getSimpleName().equals(router)) { path = config.getString("sunbird_remote_req_router_path"); return system.actorSelection(path); } else { return null; } }
Example #7
Source File: SunbirdMWService.java From sunbird-lms-service with MIT License | 5 votes |
public static void tellToBGRouter(Request request, ActorRef sender) { String operation = request.getOperation(); ActorRef actor = BackgroundRequestRouter.getActor(operation); if (null == actor) { ActorSelection select = getRemoteRouter(BackgroundRequestRouter.class.getSimpleName()); select.tell(request, sender); } else { actor.tell(request, sender); } }
Example #8
Source File: SunbirdMWService.java From sunbird-lms-service with MIT License | 5 votes |
public static void tellToRequestRouter(Request request, ActorRef sender) { String operation = request.getOperation(); ActorRef actor = RequestRouter.getActor(operation); if (null == actor) { ActorSelection select = getRemoteRouter(RequestRouter.class.getSimpleName()); select.tell(request, sender); } else { actor.tell(request, sender); } }
Example #9
Source File: UserRoleActorTest.java From sunbird-lms-service with MIT License | 5 votes |
@Before public void beforeEachTest() { PowerMockito.mockStatic(ServiceFactory.class); PowerMockito.mockStatic(BaseMWService.class); PowerMockito.mockStatic(RequestRouter.class); PowerMockito.mockStatic(InterServiceCommunicationFactory.class); PowerMockito.mockStatic(RoleDaoImpl.class); PowerMockito.mockStatic(Util.class); PowerMockito.mockStatic(UserOrgDaoImpl.class); PowerMockito.mockStatic(EsClientFactory.class); when(InterServiceCommunicationFactory.getInstance()).thenReturn(interServiceCommunication); RoleDaoImpl roleDao = Mockito.mock(RoleDaoImpl.class); when(RoleDaoImpl.getInstance()).thenReturn(roleDao); UserOrgDao userOrgDao = Mockito.mock(UserOrgDaoImpl.class); when(UserOrgDaoImpl.getInstance()).thenReturn(userOrgDao); when(userOrgDao.updateUserOrg(Mockito.anyObject())).thenReturn(getSuccessResponse()); CompletionStage completionStage = Mockito.mock(CompletionStage.class); ActorSelection actorSelection = Mockito.mock(ActorSelection.class); when(BaseMWService.getRemoteRouter(Mockito.anyString())).thenReturn(actorSelection); when(actorSelection.resolveOneCS(Duration.create(Mockito.anyLong(), "seconds"))) .thenReturn(completionStage); ActorRef actorRef = Mockito.mock(ActorRef.class); when(RequestRouter.getActor(Mockito.anyString())).thenReturn(actorRef); SearchDTO searchDTO = Mockito.mock(SearchDTO.class); when(Util.createSearchDto(Mockito.anyMap())).thenReturn(searchDTO); when(ServiceFactory.getInstance()).thenReturn(cassandraOperation); when(cassandraOperation.getAllRecords(Mockito.anyString(), Mockito.anyString())) .thenReturn(getCassandraResponse()); when(cassandraOperation.getRecordsByProperties( Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) .thenReturn(getRecordByPropertyResponse()); esService = mock(ElasticSearchRestHighImpl.class); when(EsClientFactory.getInstance(Mockito.anyString())).thenReturn(esService); }
Example #10
Source File: ConnectivityByRoundTripSignalEnrichmentProvider.java From ditto with Eclipse Public License 2.0 | 5 votes |
/** * Instantiate this provider. Called by reflection. * * @param actorSystem The actor system for which this provider is instantiated. * @param signalEnrichmentConfig Configuration for this provider. */ @SuppressWarnings("unused") public ConnectivityByRoundTripSignalEnrichmentProvider(final ActorSystem actorSystem, final SignalEnrichmentConfig signalEnrichmentConfig) { final ActorSelection commandHandler = actorSystem.actorSelection(CONCIERGE_FORWARDER); final SignalEnrichmentFacadeByRoundTripConfig config = DefaultSignalEnrichmentFacadeByRoundTripConfig.of(signalEnrichmentConfig.getProviderConfig()); byRoundTripSignalEnrichmentFacade = ByRoundTripSignalEnrichmentFacade.of(commandHandler, config.getAskTimeout()); }
Example #11
Source File: LargeMessageProxy.java From akka-tutorial with Apache License 2.0 | 5 votes |
private void handle(LargeMessage<?> message) { ActorRef receiver = message.getReceiver(); ActorSelection receiverProxy = this.context().actorSelection(receiver.path().child(DEFAULT_NAME)); // This will definitely fail in a distributed setting if the serialized message is large! // Solution options: // 1. Serialize the object and send its bytes batch-wise (make sure to use artery's side channel then). // 2. Serialize the object and send its bytes via Akka streaming. // 3. Send the object via Akka's http client-server component. // 4. Other ideas ... receiverProxy.tell(new BytesMessage<>(message.getMessage(), this.sender(), message.getReceiver()), this.self()); }
Example #12
Source File: GatewayByRoundTripSignalEnrichmentProvider.java From ditto with Eclipse Public License 2.0 | 5 votes |
/** * Instantiate this provider. Called by reflection. * * @param actorSystem The actor system for which this provider is instantiated. * @param signalEnrichmentConfig Configuration for this provider. */ public GatewayByRoundTripSignalEnrichmentProvider(final ActorSystem actorSystem, final GatewaySignalEnrichmentConfig signalEnrichmentConfig) { final ActorSelection commandHandler = actorSystem.actorSelection(CONCIERGE_FORWARDER); byRoundTripSignalEnrichmentFacade = ByRoundTripSignalEnrichmentFacade.of(commandHandler, signalEnrichmentConfig.getAskTimeout()); }
Example #13
Source File: SshClusterManagerImpl.java From java-11-examples with Apache License 2.0 | 5 votes |
public void onSessionCloseRequest(SessionCloseRequest sessionCloseRequest) { if (isLeader.get()) { LOG.info("session close request: {}", sessionCloseRequest.getSessionActorAddress()); pendingCloseSessionRequests.put(sessionCloseRequest.getClientId(), sessionCloseRequest); for (MemberInfo mi: members.values()) { String localManagerAddress = mi.getSshSessionLocalManagerAddress(sessionCloseRequest.getSshSessionId()); if (localManagerAddress != null) { ActorSelection actorSelection = actorSystem.actorSelection(localManagerAddress); actorSelection.tell(sessionCloseRequest, selfRef); break; } } } }
Example #14
Source File: SshClusterManagerImpl.java From java-11-examples with Apache License 2.0 | 5 votes |
public void onSessionCreateRequest(SessionCreateRequest sessionCreateRequest) { if (isLeader.get()) { String memberAddress = selectClusterMemberForNewSession(); ActorSelection actorSelection = actorSystem.actorSelection(Utils.getSshLocalManagerActorAddress(memberAddress)); actorSelection.tell(sessionCreateRequest, selfRef); //TODO: set timeout (circuit breaker) SessionCreateInfo sessionCreateInfo = new SessionCreateInfo(sessionCreateRequest.getClientId(), memberAddress, sessionCreateRequest.getClientActorAddress()); pendingCreateSessionRequests.put(sessionCreateRequest.getClientId(), sessionCreateInfo); } }
Example #15
Source File: FlowerActorSystem.java From flower with Apache License 2.0 | 5 votes |
protected ActorRef createRemoteActor(String actorPath) { try { ActorSelection actorSelection = actorContext.actorSelection(actorPath); ActorRef actorRef = Await.result(actorSelection.resolveOne(new FiniteDuration(3, TimeUnit.SECONDS)), Duration.create(3, TimeUnit.SECONDS)); actorContext.watch(actorRef); return actorRef; } catch (Exception e) { throw new FlowerException("fail to create remote actor, actor path : " + actorPath, e); } }
Example #16
Source File: AkkaActorITest.java From java-specialagent with Apache License 2.0 | 5 votes |
private static void testTell(final ActorSystem system) throws Exception { final ActorRef actorRef = system.actorOf(TestActor.props(false), "tell"); final CountDownLatch latch = TestUtil.initExpectedSpanLatch(4); actorRef.tell("tell", ActorRef.noSender()); final ActorSelection actorSelection = system.actorSelection(actorRef.path()); actorSelection.tell("tell-selection", ActorRef.noSender()); TestUtil.checkSpan(latch, new ComponentSpanCount("java-akka", 4)); }
Example #17
Source File: AkkaTest.java From java-specialagent with Apache License 2.0 | 5 votes |
@Test public void testTell(final MockTracer tracer) { final ActorRef actorRef = system.actorOf(TestActor.props(tracer, false), "tell"); actorRef.tell("tell", ActorRef.noSender()); final ActorSelection actorSelection = system.actorSelection(actorRef.path()); actorSelection.tell("tell-selection", ActorRef.noSender()); await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(4)); final List<MockSpan> spans = tracer.finishedSpans(); assertEquals(4, spans.size()); for (final MockSpan span : spans) assertEquals(AkkaAgentIntercept.COMPONENT_NAME, span.tags().get(Tags.COMPONENT.getKey())); }
Example #18
Source File: AkkaRpcService.java From flink with Apache License 2.0 | 5 votes |
private CompletableFuture<ActorRef> resolveActorAddress(String address) { final ActorSelection actorSel = actorSystem.actorSelection(address); return actorSel.resolveOne(TimeUtils.toDuration(configuration.getTimeout())) .toCompletableFuture() .exceptionally(error -> { throw new CompletionException( new RpcConnectionException(String.format("Could not connect to rpc endpoint under address %s.", address), error)); }); }
Example #19
Source File: CachingSignalEnrichmentFacadeTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Override protected SignalEnrichmentFacade createSignalEnrichmentFacadeUnderTest(final TestKit kit, final Duration duration) { final CacheConfig cacheConfig = DefaultCacheConfig.of(ConfigFactory.parseString(CACHE_CONFIG), CACHE_CONFIG_KEY); final ActorSelection commandHandler = ActorSelection.apply(kit.getRef(), ""); final ByRoundTripSignalEnrichmentFacade cacheLoaderFacade = ByRoundTripSignalEnrichmentFacade.of(commandHandler, Duration.ofSeconds(10L)); return CachingSignalEnrichmentFacade.of(cacheLoaderFacade, cacheConfig, kit.getSystem().getDispatcher(), "test"); }
Example #20
Source File: MessageMappingProcessorActorTest.java From ditto with Eclipse Public License 2.0 | 4 votes |
private void setUpConciergeForwarder(final ActorRef recipient) { final ActorSelection actorSelection = actorSystem.actorSelection("/user/connectivityRoot/conciergeForwarder"); Patterns.ask(actorSelection, recipient, Duration.ofSeconds(10L)) .toCompletableFuture() .join(); }
Example #21
Source File: ThingPersistenceActorTest.java From ditto with Eclipse Public License 2.0 | 4 votes |
@Test public void unavailableExpectedIfPersistenceActorTerminates() throws Exception { new TestKit(actorSystem) { { final Thing thing = createThingV2WithRandomId(); final ThingId thingId = getIdOrThrow(thing); final ActorRef underTest = createSupervisorActorFor(thingId); final CreateThing createThing = CreateThing.of(thing, null, dittoHeadersV2); underTest.tell(createThing, getRef()); final CreateThingResponse createThingResponse = expectMsgClass(CreateThingResponse.class); assertThingInResponse(createThingResponse.getThingCreated().orElse(null), thing); // retrieve created thing final RetrieveThing retrieveThing = RetrieveThing.of(thingId, dittoHeadersV2); underTest.tell(retrieveThing, getRef()); expectMsgEquals(retrieveThingResponse(thing, thing.toJson(), dittoHeadersV2)); // terminate thing persistence actor final String thingActorPath = String.format("akka://AkkaTestSystem/user/%s/pa", thingId); final ActorSelection thingActorSelection = actorSystem.actorSelection(thingActorPath); final Future<ActorRef> thingActorFuture = thingActorSelection.resolveOne(Duration.create(5, TimeUnit.SECONDS)); Await.result(thingActorFuture, Duration.create(6, TimeUnit.SECONDS)); final ActorRef thingActor = watch(thingActorFuture.value().get().get()); watch(thingActor); thingActor.tell(PoisonPill.getInstance(), getRef()); expectTerminated(thingActor); // wait for supervisor to react to termination message Thread.sleep(500L); // retrieve unavailable thing underTest.tell(retrieveThing, getRef()); expectMsgClass(ThingUnavailableException.class); } }; }
Example #22
Source File: ClientActor.java From usergrid with Apache License 2.0 | 4 votes |
@Override public void onReceive(Object message) { int startSize = nodes.size(); String routerPath = routersByMessageType.get( message.getClass() ); if ( routerPath != null && ready ) { // just pick any node, the ClusterSingletonRouter will do the consistent hash routing List<Address> nodesList = new ArrayList<>( nodes ); Address address = nodesList.get( ThreadLocalRandom.current().nextInt( nodesList.size() ) ); ActorSelection service = getContext().actorSelection( address + routerPath ); service.tell( message, getSender() ); } else if ( routerPath != null ) { logger.debug("{} responding with status unknown", name); getSender().tell( new ErrorResponse("ClientActor not ready"), getSender() ); } else if ( message instanceof StatusRequest ) { if ( ready ) { getSender().tell( new StatusMessage( name, StatusMessage.Status.READY ), getSender() ); } else { getSender().tell( new StatusMessage( name, StatusMessage.Status.INITIALIZING), getSender() ); } return; } else { processAsClusterEvent( message ); } if ( logger.isDebugEnabled() && startSize != nodes.size() ) { logger.debug( "{} now knows {} nodes", name, nodes.size() ); } if (!nodes.isEmpty() && !ready) { logger.debug( name + " is ready" ); ready = true; } else if (nodes.isEmpty() && ready) { ready = false; } }
Example #23
Source File: AkkaQueryServiceRetriever.java From Flink-CEPplus with Apache License 2.0 | 4 votes |
@Override public CompletableFuture<MetricQueryServiceGateway> retrieveService(String queryServicePath) { ActorSelection selection = actorSystem.actorSelection(queryServicePath); return FutureUtils.toJava(selection.resolveOne(FutureUtils.toFiniteDuration(lookupTimeout))).thenApply(AkkaQueryServiceGateway::new); }
Example #24
Source File: ByRoundTripSignalEnrichmentFacadeTest.java From ditto with Eclipse Public License 2.0 | 4 votes |
@Override protected SignalEnrichmentFacade createSignalEnrichmentFacadeUnderTest(final TestKit kit, final Duration duration) { final ActorSelection commandHandler = ActorSelection.apply(kit.getRef(), ""); return ByRoundTripSignalEnrichmentFacade.of(commandHandler, duration); }
Example #25
Source File: ByRoundTripSignalEnrichmentFacade.java From ditto with Eclipse Public License 2.0 | 4 votes |
private ByRoundTripSignalEnrichmentFacade(final ActorSelection commandHandler, final Duration askTimeout) { this.commandHandler = checkNotNull(commandHandler, "commandHandler"); this.askTimeout = checkNotNull(askTimeout, "askTimeout"); }
Example #26
Source File: BaseController.java From sunbird-lms-service with MIT License | 4 votes |
/** * This method will make a call to Akka actor and return CompletionStage. * * @param actorRef ActorSelection * @param request Request * @param timeout Timeout * @param responseKey String * @param httpReq play.mvc.Http.Request * @return CompletionStage<Result> */ public CompletionStage<Result> actorResponseHandler( Object actorRef, org.sunbird.common.request.Request request, Timeout timeout, String responseKey, Request httpReq) { setContextData(httpReq, request); Function<Object, Result> function = result -> { if (ActorOperations.HEALTH_CHECK.getValue().equals(request.getOperation())) { setGlobalHealthFlag(result); } if (result instanceof Response) { Response response = (Response) result; if (ResponseCode.OK.getResponseCode() == (response.getResponseCode().getResponseCode())) { return createCommonResponse(response, responseKey, httpReq); } else if (ResponseCode.CLIENT_ERROR.getResponseCode() == (response.getResponseCode().getResponseCode())) { return createClientErrorResponse(httpReq, (ClientErrorResponse) response); } else if (result instanceof ProjectCommonException) { return createCommonExceptionResponse((ProjectCommonException) result, httpReq); } else if (result instanceof File) { return createFileDownloadResponse((File) result); } else { if (StringUtils.isNotEmpty((String) response.getResult().get(JsonKey.MESSAGE)) && response.getResponseCode().getResponseCode() == 0) { return createCommonResponse(response, responseKey, httpReq); } else { return createCommonExceptionResponse((Exception) result, httpReq); } } } else if (result instanceof ProjectCommonException) { return createCommonExceptionResponse((ProjectCommonException) result, httpReq); } else if (result instanceof File) { return createFileDownloadResponse((File) result); } else { return createCommonExceptionResponse(new Exception(), httpReq); } }; if (actorRef instanceof ActorRef) { return PatternsCS.ask((ActorRef) actorRef, request, timeout).thenApplyAsync(function); } else { return PatternsCS.ask((ActorSelection) actorRef, request, timeout).thenApplyAsync(function); } }
Example #27
Source File: Reaper.java From akka-tutorial with Apache License 2.0 | 4 votes |
public static void watchWithDefaultReaper(AbstractActor actor) { ActorSelection defaultReaper = actor.getContext().getSystem().actorSelection("/user/" + DEFAULT_NAME); defaultReaper.tell(new WatchMeMessage(), actor.getSelf()); }
Example #28
Source File: Reaper.java From akka-tutorial with Apache License 2.0 | 4 votes |
public static void watchWithDefaultReaper(AbstractActor actor) { ActorSelection defaultReaper = actor.getContext().getSystem().actorSelection("/user/" + DEFAULT_NAME); defaultReaper.tell(new WatchMeMessage(), actor.getSelf()); }
Example #29
Source File: AkkaAgentIntercept.java From java-specialagent with Apache License 2.0 | 4 votes |
@SuppressWarnings("deprecation") public static Object askStart(final Object arg0, final Object message, final String method, final Object sender) { if (arg0 instanceof DeadLetterActorRef) return message; if (arg0 instanceof ActorRef && ((ActorRef)arg0).isTerminated()) return message; if (sender instanceof PromiseActorRef || arg0 instanceof PromiseActorRef) return message; if (sender instanceof ActorRef && ((ActorRef)sender).isTerminated()) return message; final String path; if (arg0 instanceof ActorRef) path = ((ActorRef)arg0).path().toString(); else if (arg0 instanceof ActorSelection) path = ((ActorSelection)arg0).toSerializationFormat(); else return message; if (path.contains("/system/")) return message; final Tracer tracer = GlobalTracer.get(); final Span span = tracer .buildSpan(method) .withTag(Tags.COMPONENT, COMPONENT_NAME) .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_PRODUCER) .withTag(Tags.MESSAGE_BUS_DESTINATION, path) .start(); final HashMap<String,String> headers = new HashMap<>(); tracer.inject(span.context(), Format.Builtin.TEXT_MAP_INJECT, headers::put); final Scope scope = tracer.activateSpan(span); LocalSpanContext.set(COMPONENT_NAME, span, scope); return new TracedMessage<>(message, headers); }
Example #30
Source File: Delegate.java From Nickle-Scheduler with Apache License 2.0 | 4 votes |
/** * 调取简单任务 * * @param job * @param nickleSchedulerExecutorJobs */ public static void scheduleSimpleJob(NickleSchedulerJob job, List<NickleSchedulerExecutorJob> nickleSchedulerExecutorJobs, SqlSessionFactory sqlSessionFactory, ActorContext actorContext) { SqlSession sqlSession = sqlSessionFactory.openSession(); NickleSchedulerExecutorMapper executorMapper = sqlSession.getMapper(NickleSchedulerExecutorMapper.class); NickleSchedulerRunJobMapper runJobMapper = sqlSession.getMapper(NickleSchedulerRunJobMapper.class); try { //简单任务目前采用轮询算法来保证任务高可用 /** * @// TODO: 2019/5/12 应修改为随机散列提高性能 */ for (NickleSchedulerExecutorJob executorJob : nickleSchedulerExecutorJobs) { //获取到执行器ip和端口 QueryWrapper<NickleSchedulerExecutor> schedulerExecutorQueryWrapper = new QueryWrapper<>(); schedulerExecutorQueryWrapper.lambda().eq(NickleSchedulerExecutor::getExecutorName, executorJob.getExecutorName()); NickleSchedulerExecutor nickleSchedulerExecutor = executorMapper.selectOne(schedulerExecutorQueryWrapper); if (nickleSchedulerExecutor == null) { log.error("关联表有执行器,但是执行器表没有对应执行器数据"); continue; } //插入正在巡行列表 NickleSchedulerRunJob nickleSchedulerRunJob = insertRunJob(sqlSession, nickleSchedulerExecutor.getExecutorId(), job); //拼接获取远程actor发送信息 String executorDispatcherPath = String.format(AKKA_REMOTE_MODEL , EXECUTOR_SYSTEM_NAME , nickleSchedulerExecutor.getExecutorIp() , nickleSchedulerExecutor.getExecutorPort() , EXECUTOR_DISPATCHER_NAME); ActorSelection actorSelection = actorContext.actorSelection(executorDispatcherPath); ExecuteJobEvent executorStartEvent = new ExecuteJobEvent(job.getJobClassName(), nickleSchedulerRunJob.getId()); log.info("开始调度简单job:{},目标主机路径:{}", job, executorDispatcherPath); log.info("executorStartEvent:{}", executorStartEvent); //需确保DispacherActor真实收到任务所以采用ask模式,超时时间设置500ms Timeout t = new Timeout(Duration.create(500, TimeUnit.MILLISECONDS)); CountDownLatch countDownLatch = new CountDownLatch(1); Future<Object> ask = Patterns.ask(actorSelection, executorStartEvent, t); boolean[] registerSuccess = new boolean[1]; registerSuccess[0] = false; ask.onComplete(new OnComplete<Object>() { @Override public void onComplete(Throwable throwable, Object o) throws Throwable { if (throwable != null) { log.error("执行器:{}连接超时,即将删除", nickleSchedulerExecutor); //删除执行器 deleteExecutor(sqlSession, nickleSchedulerExecutor); log.error("执行器:{}删除成功", nickleSchedulerExecutor); } else { registerSuccess[0] = true; } countDownLatch.countDown(); } }, actorContext.dispatcher()); //等待任务注册完毕 try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } if (registerSuccess[0]) { log.info("job:{}调度成功", job); sqlSession.commit(); return; } else { runJobMapper.deleteById(nickleSchedulerRunJob.getId()); log.info("job:{}调度失败,执行器为:{}", job, nickleSchedulerExecutor); } } //执行到这里证明所有执行器都无法连接,将会把任务失败 insertFailJob(job, NO_EXECUTOR, EXECUTOR_NOT_CONNECTED, sqlSession); sqlSession.commit(); } finally { sqlSession.close(); } }