com.netflix.hystrix.HystrixCommand Java Examples
The following examples show how to use
com.netflix.hystrix.HystrixCommand.
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: PreparationAPI.java From data-prep with Apache License 2.0 | 6 votes |
/** * Moves the step of specified id <i>stepId</i> after step of specified id <i>parentId</i> within the specified * preparation. * * @param preparationId the Id of the specified preparation * @param stepId the Id of the specified step to move * @param parentStepId the Id of the specified step which will become the parent of the step to move */ // formatter:off @RequestMapping(value = "/api/preparations/{preparationId}/steps/{stepId}/order", method = POST, consumes = APPLICATION_JSON_VALUE) @ApiOperation(value = "Moves a step within a preparation just after the specified <i>parentStepId</i>", notes = "Moves a step within a preparation.") @Timed public void moveStep(@PathVariable("preparationId") final String preparationId, @ApiParam(value = "The current index of the action we want to move.") @PathVariable("stepId") String stepId, @ApiParam(value = "The current index of the action we want to move.") @RequestParam String parentStepId) { //@formatter:on LOG.info("Moving step {} after step {}, within preparation {}", stepId, parentStepId, preparationId); final HystrixCommand<String> command = getCommand(PreparationReorderStep.class, preparationId, stepId, parentStepId); command.execute(); LOG.debug("Step {} moved after step {}, within preparation {}", stepId, parentStepId, preparationId); }
Example #2
Source File: CommandHelper.java From data-prep with Apache License 2.0 | 6 votes |
public static StreamingResponseBody toStreaming(final HystrixCommand<InputStream> command) { return outputStream -> { final Observable<InputStream> stream = command.toObservable(); stream.toBlocking().subscribe(inputStream -> { try { IOUtils.copyLarge(inputStream, outputStream); outputStream.flush(); } catch (IOException e) { try { inputStream.close(); } catch (IOException closingException) { LOGGER.warn("could not close command result, a http connection may be leaked !", closingException); } LOGGER.error("Unable to fully copy command result '{}'.", command.getClass(), e); } }, TDPException::rethrowOrWrap); }; }
Example #3
Source File: PaymentRestHacksControllerV3.java From flowing-retail with Apache License 2.0 | 6 votes |
@Override public void handle(JobClient client, ActivatedJob job) throws Exception { CreateChargeRequest request = new CreateChargeRequest(); request.amount = (int) job.getVariablesAsMap().get("amount"); CreateChargeResponse response = new HystrixCommand<CreateChargeResponse>(HystrixCommandGroupKey.Factory.asKey("stripe")) { protected CreateChargeResponse run() throws Exception { return rest.postForObject( // stripeChargeUrl, // request, // CreateChargeResponse.class); } }.execute(); client.newCompleteCommand(job.getKey()) // .variables(Collections.singletonMap("paymentTransactionId", response.transactionId)) .send().join(); }
Example #4
Source File: TenacityAuthenticatorTest.java From tenacity with Apache License 2.0 | 6 votes |
@Test public void shouldLogWhenExceptionIsThrown() throws AuthenticationException { final DefaultExceptionLogger defaultExceptionLogger = spy(new DefaultExceptionLogger()); HystrixPlugins.getInstance().registerCommandExecutionHook(new ExceptionLoggingCommandHook(defaultExceptionLogger)); when(mockAuthenticator.authenticate(any(BasicCredentials.class))).thenThrow(new AuthenticationException("test")); doCallRealMethod().when(defaultExceptionLogger).log(any(Exception.class), any(HystrixCommand.class)); try { tenacityAuthenticator.authenticate(new BasicCredentials("foo", "foo")); } catch (HystrixRuntimeException err) { assertThat(Throwables.getCausalChain(err) .stream() .filter(AuthenticationException.class::isInstance) .findAny()) .isNotEmpty(); } verify(mockAuthenticator, times(1)).authenticate(any(BasicCredentials.class)); verify(defaultExceptionLogger, times(1)).log(any(Exception.class), any(HystrixCommand.class)); }
Example #5
Source File: HystrixCommand_1_4_0_to_1_5_2_IT.java From pinpoint with Apache License 2.0 | 6 votes |
@Test public void hystrixCommand_observe() throws Exception { hystrixCommandTestRunner.observe(); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.ignoreServiceType("RX_JAVA", "RX_JAVA_INTERNAL"); HystrixTestHelper.verifyHystrixMetricsInitialization(verifier, SayHelloCommand.class.getSimpleName(), COMMAND_GROUP); verifier.verifyTrace(event("HYSTRIX_COMMAND", "com.netflix.hystrix.AbstractCommand.observe()", annotation("hystrix.command", SayHelloCommand.class.getSimpleName()))); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", "com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator.call(rx.Subscriber)")); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", "com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler$HystrixContextSchedulerWorker.schedule(rx.functions.Action0)")); // execution verifier.verifyTrace(event(ServiceType.ASYNC.getName(), "Asynchronous Invocation")); Method getExecutionObservable = HystrixCommand.class.getDeclaredMethod("getExecutionObservable"); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", getExecutionObservable)); Method helloMethod = HelloRepository.class.getDeclaredMethod("hello", String.class); verifier.verifyTrace(event(ServiceType.INTERNAL_METHOD.getName(), helloMethod)); verifier.verifyTraceCount(0); }
Example #6
Source File: PaymentRestHacksControllerV2.java From flowing-retail with Apache License 2.0 | 6 votes |
public String chargeCreditCard(String customerId, long remainingAmount) { CreateChargeRequest request = new CreateChargeRequest(); request.amount = remainingAmount; CreateChargeResponse response = new HystrixCommand<CreateChargeResponse>(HystrixCommandGroupKey.Factory.asKey("stripe")) { protected CreateChargeResponse run() throws Exception { return rest.postForObject( // stripeChargeUrl, // request, // CreateChargeResponse.class); } }.execute(); return response.transactionId; }
Example #7
Source File: PaymentRestHacksControllerV4b.java From flowing-retail with Apache License 2.0 | 6 votes |
@FailingOnLastRetry public void execute(DelegateExecution ctx) throws Exception { CreateChargeRequest request = new CreateChargeRequest(); request.amount = (long) ctx.getVariable("amount"); CreateChargeResponse response = new HystrixCommand<CreateChargeResponse>(HystrixCommandGroupKey.Factory.asKey("stripe")) { protected CreateChargeResponse run() throws Exception { return rest.postForObject( // stripeChargeUrl, // request, // CreateChargeResponse.class); } }.execute(); ctx.setVariable("paymentTransactionId", response.transactionId); }
Example #8
Source File: PreparationAPI.java From data-prep with Apache License 2.0 | 6 votes |
/** * Copy the steps from the another preparation to this one. * <p> * This is only allowed if this preparation has no steps. * * @param id the preparation id to update. * @param from the preparation id to copy the steps from. */ //@formatter:off @RequestMapping(value = "/api/preparations/{id}/steps/copy", method = PUT) @ApiOperation(value = "Copy the steps from another preparation", notes = "Copy the steps from another preparation if this one has no steps.") @Timed public void copyStepsFrom(@ApiParam(value="the preparation id to update") @PathVariable("id")String id, @ApiParam(value = "the preparation to copy the steps from.") @RequestParam String from) { //@formatter:on LOG.debug("copy preparations steps from {} to {}", from, id); final HystrixCommand<Void> command = getCommand(PreparationCopyStepsFrom.class, id, from); command.execute(); LOG.info("preparation's steps copied from {} to {}", from, id); }
Example #9
Source File: HystrixCommand_1_5_3_to_1_5_x_IT.java From pinpoint with Apache License 2.0 | 6 votes |
@Test public void hystrixCommand_observe() throws Exception { hystrixCommandTestRunner.observe(); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.ignoreServiceType("RX_JAVA", "RX_JAVA_INTERNAL"); HystrixTestHelper.verifyHystrixMetricsInitialization(verifier, SayHelloCommand.class.getSimpleName(), COMMAND_GROUP); verifier.verifyTrace(event("HYSTRIX_COMMAND", "com.netflix.hystrix.AbstractCommand.observe()", annotation("hystrix.command", SayHelloCommand.class.getSimpleName()))); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", "com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator.call(rx.Subscriber)")); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", "com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler$HystrixContextSchedulerWorker.schedule(rx.functions.Action0)")); // execution verifier.verifyTrace(event(ServiceType.ASYNC.getName(), "Asynchronous Invocation")); Method getExecutionObservable = HystrixCommand.class.getDeclaredMethod("getExecutionObservable"); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", getExecutionObservable)); Method helloMethod = HelloRepository.class.getDeclaredMethod("hello", String.class); verifier.verifyTrace(event(ServiceType.INTERNAL_METHOD.getName(), helloMethod)); verifier.verifyTraceCount(0); }
Example #10
Source File: TransformAPI.java From data-prep with Apache License 2.0 | 6 votes |
/** * Get the suggested action dynamic params. Dynamic params depends on the context (dataset / preparation / actual * transformations) */ @RequestMapping(value = "/api/transform/suggest/{action}/params", method = GET, produces = APPLICATION_JSON_VALUE) @ApiOperation(value = "Get the transformation dynamic parameters", notes = "Returns the transformation parameters.") @Timed public ResponseEntity<StreamingResponseBody> suggestActionParams( @ApiParam(value = "Transformation name.") @PathVariable("action") final String action, @ApiParam( value = "Suggested dynamic transformation input (preparation id or dataset id") @Valid final DynamicParamsInput dynamicParamsInput) { // get preparation/dataset content HystrixCommand<InputStream> inputData; final String preparationId = dynamicParamsInput.getPreparationId(); if (isNotBlank(preparationId)) { inputData = new AsyncGet<>( () -> getCommand(PreparationGetContent.class, preparationId, dynamicParamsInput.getStepId()), commonAPI); } else { inputData = datasetClient.getDataSetGetCommand(dynamicParamsInput.getDatasetId(), false, false); } // get params, passing content in the body final GenericCommand<InputStream> getActionDynamicParams = getCommand(SuggestActionParams.class, inputData, action, dynamicParamsInput.getColumnId()); return CommandHelper.toStreaming(getActionDynamicParams); }
Example #11
Source File: PreparationAPI.java From data-prep with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/api/preparations/{id}/head/{headId}", method = PUT) @ApiOperation(value = "Changes the head of the preparation.", notes = "Does not return any value, client may expect successful operation based on HTTP status code.") @Timed public void setPreparationHead(@PathVariable(value = "id") @ApiParam(name = "id", value = "Preparation id.") final String preparationId, @PathVariable(value = "headId") @ApiParam(name = "headId", value = "New head step id") final String headId) { //@formatter:on if (LOG.isDebugEnabled()) { LOG.debug("Moving preparation #{} head to step '{}'...", preparationId, headId); } Step step = getCommand(FindStep.class, headId).execute(); if (step == null) { throw new TDPException(PREPARATION_STEP_DOES_NOT_EXIST); } else if (isHeadStepDependingOnDeletedDataSet(preparationId, step.id())) { final HystrixCommand<Void> command = getCommand(PreparationMoveHead.class, preparationId, headId); command.execute(); } else { throw new TDPException(INVALID_HEAD_STEP_USING_DELETED_DATASET); } if (LOG.isDebugEnabled()) { LOG.debug("Moved preparation #{} head to step '{}'...", preparationId, headId); } }
Example #12
Source File: PreparationAPI.java From data-prep with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/api/preparations/{id}/actions/{stepId}", method = DELETE, produces = APPLICATION_JSON_VALUE) @ApiOperation(value = "Delete an action in the preparation.", notes = "Does not return any value, client may expect successful operation based on HTTP status code.") @Timed public void deletePreparationAction( @PathVariable(value = "id") @ApiParam(name = "id", value = "Preparation id.") final String preparationId, @PathVariable(value = "stepId") @ApiParam(name = "stepId", value = "Step id to delete.") final String stepId) { if (LOG.isDebugEnabled()) { LOG.debug("Deleting preparation action at step #{} (pool: {} ) ...", stepId, // getConnectionStats()); } final HystrixCommand<Void> command = getCommand(PreparationDeleteAction.class, preparationId, stepId); command.execute(); if (LOG.isDebugEnabled()) { LOG.debug("Deleted preparation action at step #{} (pool: {} ) ...", stepId, // getConnectionStats()); } }
Example #13
Source File: HystrixCommand_1_5_3_to_1_5_x_IT.java From pinpoint with Apache License 2.0 | 6 votes |
@Test public void hystrixCommand_execute() throws Exception { hystrixCommandTestRunner.execute(); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.ignoreServiceType("RX_JAVA", "RX_JAVA_INTERNAL"); HystrixTestHelper.verifyHystrixMetricsInitialization(verifier, SayHelloCommand.class.getSimpleName(), COMMAND_GROUP); Method executeMethod = HystrixCommand.class.getDeclaredMethod("execute"); verifier.verifyTrace(event("HYSTRIX_COMMAND", executeMethod, annotation("hystrix.command", SayHelloCommand.class.getSimpleName()))); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", "com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator.call(rx.Subscriber)")); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", "com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler$HystrixContextSchedulerWorker.schedule(rx.functions.Action0)")); // execution verifier.verifyTrace(event(ServiceType.ASYNC.getName(), "Asynchronous Invocation")); Method getExecutionObservable = HystrixCommand.class.getDeclaredMethod("getExecutionObservable"); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", getExecutionObservable)); Method helloMethod = HelloRepository.class.getDeclaredMethod("hello", String.class); verifier.verifyTrace(event(ServiceType.INTERNAL_METHOD.getName(), helloMethod)); verifier.verifyTraceCount(0); }
Example #14
Source File: HystrixCommand_1_5_3_to_1_5_x_IT.java From pinpoint with Apache License 2.0 | 6 votes |
@Test public void hystrixCommand_execute_shortCircuit() throws Exception { hystrixCommandTestRunner.executeWithShortCircuit(); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.ignoreServiceType("RX_JAVA", "RX_JAVA_INTERNAL"); HystrixTestHelper.verifyHystrixMetricsInitialization(verifier, SayHelloCommand.class.getSimpleName(), COMMAND_GROUP); Method executeMethod = HystrixCommand.class.getDeclaredMethod("execute"); verifier.verifyTrace(event("HYSTRIX_COMMAND", executeMethod, annotation("hystrix.command", SayHelloCommand.class.getSimpleName()))); // fallback due to short circuit ExpectedAnnotation fallbackCauseAnnotation = annotation("hystrix.command.fallback.cause", "short-circuited"); ExpectedAnnotation exceptionAnnotation = annotation("hystrix.command.exception", HystrixTestHelper.SHORT_CIRCUIT_EXCEPTION.toString()); verifier.verifyTrace(event( "HYSTRIX_COMMAND_INTERNAL", "com.netflix.hystrix.AbstractCommand.getFallbackOrThrowException(com.netflix.hystrix.AbstractCommand, com.netflix.hystrix.HystrixEventType, com.netflix.hystrix.exception.HystrixRuntimeException$FailureType, java.lang.String, java.lang.Exception)", fallbackCauseAnnotation, exceptionAnnotation)); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", "com.netflix.hystrix.HystrixCommand.getFallbackObservable()")); verifier.verifyTraceCount(0); }
Example #15
Source File: Demo.java From hystrix-context-spring-boot-starter with Apache License 2.0 | 6 votes |
@Test public void shouldPropagateMdcContext() { // given MDC.put(REQUEST_ID, requestId); // when final Object result = new HystrixCommand<Object>(commandGroup(GROUP_KEY)) { @Override protected Object run() throws Exception { return MDC.get(REQUEST_ID); } }.execute(); // then assertEquals(requestId, result); }
Example #16
Source File: SetterFactoryTest.java From feign with Apache License 2.0 | 6 votes |
@Test public void customSetter() { thrown.expect(HystrixRuntimeException.class); thrown.expectMessage("POST / failed and no fallback available."); server.enqueue(new MockResponse().setResponseCode(500)); SetterFactory commandKeyIsRequestLine = (target, method) -> { String groupKey = target.name(); String commandKey = method.getAnnotation(RequestLine.class).value(); return HystrixCommand.Setter .withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey)) .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey)); }; TestInterface api = HystrixFeign.builder() .setterFactory(commandKeyIsRequestLine) .target(TestInterface.class, "http://localhost:" + server.getPort()); api.invoke(); }
Example #17
Source File: ExceptionLoggingCommandHookIntegrationTest.java From tenacity with Apache License 2.0 | 5 votes |
@Test public void loggerDoesntLogIfItsNotExpected() throws Exception { HystrixPlugins.getInstance().registerCommandExecutionHook(new ExceptionLoggingCommandHook(exceptionLogger)); final HystrixCommand<String> failingCommand = new TenacityFailingWithIOException(); failingCommand.execute(); final List<RuntimeException> loggedExceptions = exceptionLogger.getLoggedExceptions(); assertTrue(loggedExceptions.isEmpty()); }
Example #18
Source File: HystrixExamples.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
public void exampleHystrix3(Vertx vertx) { vertx.runOnContext(v -> { Context context = vertx.getOrCreateContext(); HystrixCommand<String> command = getSomeCommandInstance(); command.observe().subscribe(result -> { context.runOnContext(v2 -> { // Back on context (event loop or worker) String r = result; }); }); }); }
Example #19
Source File: HystrixBuilderTest.java From feign with Apache License 2.0 | 5 votes |
@Test public void hystrixCommandIntFallback() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(); final HystrixCommand<Integer> command = api.intCommand(); assertThat(command).isNotNull(); assertThat(command.execute()).isEqualTo(new Integer(0)); }
Example #20
Source File: FolderAPI.java From data-prep with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/api/folders/tree", method = GET) @ApiOperation(value = "List all folders", produces = APPLICATION_JSON_VALUE) @Timed public StreamingResponseBody getTree() { try { final HystrixCommand<InputStream> foldersList = getCommand(FolderTree.class); return CommandHelper.toStreaming(foldersList); } catch (Exception e) { throw new TDPException(APIErrorCodes.UNABLE_TO_LIST_FOLDERS, e); } }
Example #21
Source File: HystrixCommandTestRunner.java From pinpoint with Apache License 2.0 | 5 votes |
public void observe() throws Exception { final String name = "Pinpoint"; final String expectedMessage = HystrixTestHelper.sayHello(name); HystrixCommand<String> helloCommand = SayHelloCommand.create(commandGroup, name); List<String> actualMessages = helloCommand.observe().toList().toBlocking().single(); Assert.assertTrue(actualMessages.size() == 1); Assert.assertEquals(expectedMessage, actualMessages.get(0)); HystrixTestHelper.waitForSpanDataFlush(); }
Example #22
Source File: HystrixCommandTestRunner.java From pinpoint with Apache License 2.0 | 5 votes |
public void execute() throws Exception { final String name = "Pinpoint"; final String expectedMessage = HystrixTestHelper.sayHello(name); HystrixCommand<String> helloCommand = SayHelloCommand.create(commandGroup, name); String actualMessage = helloCommand.execute(); Assert.assertEquals(expectedMessage, actualMessage); HystrixTestHelper.waitForSpanDataFlush(); }
Example #23
Source File: HystrixCommand_1_4_0_to_1_5_2_IT.java From pinpoint with Apache License 2.0 | 5 votes |
@Test public void hystrixCommand_execute_timeout() throws Exception { hystrixCommandTestRunner.executeWithTimeout(); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.ignoreServiceType("RX_JAVA", "RX_JAVA_INTERNAL"); HystrixTestHelper.verifyHystrixMetricsInitialization(verifier, SayHelloCommand.class.getSimpleName(), COMMAND_GROUP); Method executeMethod = HystrixCommand.class.getDeclaredMethod("execute"); verifier.verifyTrace(event("HYSTRIX_COMMAND", executeMethod, annotation("hystrix.command", SayHelloCommand.class.getSimpleName()))); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", "com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator.call(rx.Subscriber)")); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", "com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler$HystrixContextSchedulerWorker.schedule(rx.functions.Action0)")); // fallback due to timeout verifier.verifyTrace(event(ServiceType.ASYNC.getName(), "Asynchronous Invocation")); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", "Hystrix Command Timeout tick")); ExpectedAnnotation fallbackCauseAnnotation = annotation("hystrix.command.fallback.cause", "timed-out"); ExpectedAnnotation exceptionAnnotation = annotation("hystrix.command.exception", new TimeoutException().toString()); verifier.verifyTrace(event( "HYSTRIX_COMMAND_INTERNAL", "com.netflix.hystrix.AbstractCommand.getFallbackOrThrowException(com.netflix.hystrix.HystrixEventType, com.netflix.hystrix.exception.HystrixRuntimeException$FailureType, java.lang.String, java.lang.Exception)", fallbackCauseAnnotation, exceptionAnnotation)); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", "com.netflix.hystrix.HystrixCommand.getFallbackObservable()")); // execution verifier.awaitTraceCount(3, 20, 3000); verifier.verifyTrace(event(ServiceType.ASYNC.getName(), "Asynchronous Invocation")); Method getExecutionObservable = HystrixCommand.class.getDeclaredMethod("getExecutionObservable"); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", getExecutionObservable)); Method helloMethod = HelloRepository.class.getDeclaredMethod("hello", String.class, long.class); verifier.verifyTrace(event(ServiceType.INTERNAL_METHOD.getName(), helloMethod, HystrixTestHelper.INTERRUPTED_EXCEPTION_DUE_TO_TIMEOUT)); verifier.verifyTraceCount(0); }
Example #24
Source File: AbstractVersionSupplier.java From data-prep with Apache License 2.0 | 5 votes |
/** * Call the version service on the given service: dataset, preparation or transformation. * * @param serviceName the name of the service * @return the version of the called service */ protected Version callVersionService(String serviceUrl, String serviceName, String entryPoint) { HystrixCommand<Version> versionCommand = context.getBean(VersionCommand.class, serviceUrl, entryPoint); final Version version = versionCommand.execute(); version.setServiceName(serviceName); return version; }
Example #25
Source File: HystrixMetricsTest.java From javabase with Apache License 2.0 | 5 votes |
public static void main(String[] args) { CommandConfig.Setter setter = HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("HystrixMetrics-config")); setter.andCommandKey(HystrixCommandKey.Factory.asKey("HystrixMetrics-method")); //在调用方配置,被该调用方的所有方法的超时时间都是该值 HystrixCommandProperties.Setter defaultSetter = HystrixCommandProperties.Setter(); setter.andCommandPropertiesDefaults(defaultSetter); Observable<HystrixDashboardStream.DashboardData> dashboardDataOservable = HystrixDashboardStream.getInstance().observe(); Observable<String> sampleStream = dashboardDataOservable.concatMap(new Func1<HystrixDashboardStream.DashboardData, Observable<String>>() { public Observable<String> call(HystrixDashboardStream.DashboardData dashboardData) { return Observable.from(SerialHystrixDashboardData.toMultipleJsonStrings(dashboardData)); } }); Subscription sampleSubscription = sampleStream.observeOn(Schedulers.io()).subscribe(new Subscriber<String>() { @Override public void onCompleted() { } @Override public void onError(Throwable throwable) { } @Override public void onNext(String sampleDataAsString) { log.info("sampleDataAsString=" + sampleDataAsString); } }); if (sampleSubscription.isUnsubscribed()) { sampleSubscription.unsubscribe(); } for (; ; ) { new MetricsCommand(setter).execute(); } }
Example #26
Source File: DataSetAPI.java From data-prep with Apache License 2.0 | 5 votes |
/** * Create a dataset from request body content. * * @param name The dataset name. * @param contentType the request content type used to distinguish dataset creation or import. * @param dataSetContent the dataset content from the http request body. * @return The dataset id. */ @RequestMapping(value = "/api/datasets", method = POST, produces = TEXT_PLAIN_VALUE) @ApiOperation(value = "Create a data set", produces = TEXT_PLAIN_VALUE, notes = "Create a new data set based on content provided in POST body. For documentation purposes, body is typed as 'text/plain' but operation accepts binary content too. Returns the id of the newly created data set.") @Timed public Callable<String> create( @ApiParam( value = "User readable name of the data set (e.g. 'Finance Report 2015', 'Test Data Set').") @RequestParam( defaultValue = "", required = false) final String name, @ApiParam(value = "An optional tag to be added in data set metadata once created.") @RequestParam( defaultValue = "", required = false) String tag, @ApiParam(value = "Size of the data set, in bytes.") @RequestParam(defaultValue = "0") long size, @RequestHeader(CONTENT_TYPE) String contentType, @ApiParam(value = "content") InputStream dataSetContent) { return () -> { if (LOG.isDebugEnabled()) { LOG.debug("Creating dataset (pool: {} )...", getConnectionStats()); } try { HystrixCommand<String> creation = getCommand(CreateDataSet.class, StringsHelper.normalizeString(name), tag, contentType, size, dataSetContent); return creation.execute(); } finally { LOG.debug("Dataset creation done."); } }; }
Example #27
Source File: AppSettingsConfigurer.java From data-prep with Apache License 2.0 | 5 votes |
/** * Get hystrix command */ protected <S extends HystrixCommand> S getCommand(Class<S> clazz, Object... args) { try { return context.getBean(clazz, args); } catch (BeansException e) { throw new TDPException(APIErrorCodes.UNABLE_TO_FIND_COMMAND, e, ExceptionContext.build().put("class", clazz).put("args", args)); } }
Example #28
Source File: TwitchHelix.java From twitch4j with MIT License | 5 votes |
/** * Replaces the active stream tags on the specified stream with the specified tags (or clears all tags, if no new tags are specified). * Requires scope: user:edit:broadcast * * @param authToken Auth Token * @param broadcasterId ID of the stream to replace tags for * @param tagIds Tag ids to replace the current stream tags with. Maximum: 100. If empty, all tags are cleared from the stream. Tags currently expire 72 hours after they are applied, unless the stream is live within that time period. * @return Object nothing */ @RequestLine("PUT /streams/tags?broadcaster_id={broadcaster_id}") @Headers({ "Authorization: Bearer {token}", "Content-Type: application/json" }) @Body("%7B\"tag_ids\": [{tag_ids}]%7D") HystrixCommand<Void> replaceStreamTags( @Param("token") String authToken, @Param("broadcaster_id") String broadcasterId, @Param(value = "tag_ids", expander = ObjectToJsonExpander.class) List<UUID> tagIds );
Example #29
Source File: FolderAPI.java From data-prep with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/api/folders", method = PUT) @ApiOperation(value = "Add a folder.", produces = APPLICATION_JSON_VALUE) @Timed public StreamingResponseBody addFolder(@RequestParam(required = false) final String parentId, @RequestParam final String path) { try { final HystrixCommand<InputStream> createChildFolder = getCommand(CreateChildFolder.class, parentId, path); return CommandHelper.toStreaming(createChildFolder); } catch (Exception e) { throw new TDPException(APIErrorCodes.UNABLE_TO_CREATE_FOLDER, e); } }
Example #30
Source File: PreparationAPI.java From data-prep with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/api/preparations/{preparationId}/actions/{stepId}", method = PUT, produces = APPLICATION_JSON_VALUE) @ApiOperation(value = "Updates an action in the preparation.", notes = "Does not return any value, client may expect successful operation based on HTTP status code.") @Timed public void updatePreparationAction(@ApiParam(name = "preparationId", value = "Preparation id.") @PathVariable(value = "preparationId") final String preparationId, @ApiParam(name = "stepId", value = "Step id in the preparation.") @PathVariable(value = "stepId") final String stepId, @ApiParam("New content for the action.") @RequestBody final AppendStep step) { //@formatter:on if (LOG.isDebugEnabled()) { LOG.debug("Updating preparation action at step #{} (pool: {} )...", stepId, getConnectionStats()); } // get the preparation PreparationDTO preparation = internalGetPreparation(preparationId); // get the preparation actions for up to the updated action final int stepIndex = new ArrayList<>(preparation.getSteps()).indexOf(stepId); final String parentStepId = preparation.getSteps().get(stepIndex - 1); final PreparationGetActions getActionsCommand = getCommand(PreparationGetActions.class, preparationId, parentStepId); // get the diff final DiffMetadata diffCommand = getCommand(DiffMetadata.class, preparation.getDataSetId(), preparationId, step.getActions(), getActionsCommand); // get the update action command and execute it final HystrixCommand<Void> command = getCommand(PreparationUpdateAction.class, preparationId, stepId, step, diffCommand); command.execute(); if (LOG.isDebugEnabled()) { LOG.debug("Updated preparation action at step #{} (pool: {} )...", stepId, getConnectionStats()); } }