/** * Combine the given promises into a single promise for the list of results. * <p> * The sequencing operations are performed in the default ExecutionContext. * * @param promises The promises to combine * @return A single promise whose methods act on the list of redeemed promises * Use {@link Futures#sequence(Iterable)} instead. */ public static <A> Promise<List<A>> sequence(Iterable<Promise<A>> promises) { return wrap(Futures.sequence(promises)); }
public static <A> Promise<A> wrap(CompletionStage<A> future) { return new Promise<>(future); }
/** * Gets the Scala Future wrapped by this Promise. * * @return The Scala Future * Promise no longer wraps a Scala Future, use asScala instead. */ public Future<A> wrapped() { return asScala(); }
/** * Completes this promise with the specified Promise, once that Promise is completed. * * @param other The value to complete with * @return A promise giving the result of attempting to complete this promise with the other * promise. If the completion was successful then the result will be true, if the * completion couldn't occur then the result will be false. */ public Promise<Boolean> tryCompleteWith(Promise<? extends A> other) { return new Promise<>(other.handle((a, error) -> { if (error != null) { return future.completeExceptionally(error); } else { return future.complete(a); } })); }
/** * Completes this promise with the specified Promise, once that Promise is completed. * * @param other The value to complete with * @param ec An execution context * @return A promise giving the result of attempting to complete this promise with the other * promise. If the completion was successful then the result will be true, if the * completion couldn't occur then the result will be false. */ public Promise<Boolean> tryCompleteWith(Promise<? extends A> other, Executor ec) { return new Promise<>(other.handleAsync((a, error) -> { if (error != null) { return future.completeExceptionally(error); } else { return future.complete(a); } }, ec)); } }
public void makeInvoke(Server server, HttpUriRequest request, HTTPHandler handler){ try { HttpHost host = determineTarget(request); if(server != null) host = new HttpHost(server.getHost(),server.getPort(),host.getSchemeName()); Span span = tracer.nextSpan().name("HTTPInvoker.invoke").kind(Span.Kind.CLIENT).start(); span.tag("server",server == null ? host.getHostName() : server.getHostPort()); span.tag("attempt_count",context.getAttemptCount() + ""); String reqUri = request.getURI().toString(); if(LOGGER.isInfoEnabled()) { LOGGER.info(request.toString()); } propagationTraceInfo(request, span); Promise<HttpResponse> promise = httpClient.execute(host,request); promise.onRedeem(new SuccessCallback(span,handler,this,retryHandler), Promise.toExecutor(executionContext)); promise.onFailure(new FailureCallback(reqUri,span,handler,this,retryHandler),Promise.toExecutor(executionContext)); } catch (Throwable e) { handler.onThrowable(e); LOGGER.error("{} http error,with request:{},server:{}",httpClient.getName(),request,server); } }
httpclient.execute(req, new NFutureCallback(circuitBreaker, xPromise)); return Promise.wrap(xPromise.future()); }else{ Throwable shortCircuitException = new RuntimeException("Hystrix circuit short-circuited and is OPEN"); HystrixRuntimeException exception = new HystrixRuntimeException(HystrixRuntimeException.FailureType.SHORTCIRCUIT,null,"short-circuited",shortCircuitException,null); return Promise.throwing(exception); circuitBreaker.markFailure(); return Promise.throwing(e);
/** * Combines the current promise with <code>another</code> promise using `or`. * * @param another promise that will be combined * Use {@link #applyToEither(CompletionStage, Function)} instead. */ public <B> Promise<Either<A, B>> or(Promise<B> another) { return new Promise<>(wrapped.thenApply(Either::<A, B>Left) .applyToEither(another.thenApply(Either::<A, B>Right), Function.identity())); }
/** * Creates a new promise which holds the result of this promise if it was completed successfully, * otherwise the result of the {@code fallback} promise if it completed successfully. * If both promises failed, the resulting promise holds the throwable of this promise. * * @param fallback The promise to fallback to if this promise has failed * @return A promise that will delegate to another promise on failure * Use {@link #handleAsync(BiFunction)} followed by {@link #thenCompose(Function)} * with the identity function. */ public Promise<A> fallbackTo(final Promise<A> fallback) { return new Promise<>(wrapped.handle((a, error) -> { if (error != null) { return fallback.handle((fallbackA, fallbackError) -> { if (fallbackError != null) { CompletableFuture<A> failed = new CompletableFuture<>(); failed.completeExceptionally(error); return failed; } else { return CompletableFuture.completedFuture(fallbackA); } }).thenCompose(Function.identity()); } else { return CompletableFuture.completedFuture(a); } }).thenCompose(Function.identity())); }
/** * Awaits for the promise to get the result.<br> * Throws a Throwable if the calculation providing the promise threw an exception * * @param timeout A user defined timeout in milliseconds * @return The promised result * Calling get on a promise is a blocking operation and so introduces the risk of deadlocks * and has serious performance implications. * @throws PromiseTimeoutException when the promise did timeout. */ public A get(long timeout) { return get(timeout, TimeUnit.MILLISECONDS); }
/** * 需要处理协议转换的错误 * @author 尹有松 * @param p * @return */ public static <A extends TBase> Promise<Result> toResult(Promise<A> p){ return p.map(a -> { byte[] bytes = Thrifts.toBytes(a); return Results.ok(bytes); }); }
/** * Create a new pure promise, that is, a promise with a constant value from the start. * * @param a the value for the promise * Use {@link CompletableFuture#completedFuture(Object)} instead. */ public static <A> Promise<A> pure(final A a) { return new Promise<>(CompletableFuture.completedFuture(a)); }
/** * Create a Promise timer that throws a PromiseTimeoutException after * a given timeout. * <p> * The returned Promise is usually combined with other Promises. * * @param delay The delay expressed in milliseconds. * Use {@link Futures#timeout(long, TimeUnit)} instead. * @return a promise without a real value */ public static Promise<Void> timeout(long delay) { return wrap(Futures.timeout(delay, TimeUnit.MILLISECONDS)); }
/** * Create a Promise which will be redeemed with the result of a given function. * * @param function Used to fulfill the Promise. * @param ec The ExecutionContext to run the function in. * Use {@link CompletableFuture#supplyAsync(Supplier, Executor)} instead. */ public static <A> Promise<A> promise(Supplier<A> function, Executor ec) { return new Promise<>(CompletableFuture.supplyAsync(function, (ec))); }
/** * Combine the given promises into a single promise for the list of results. * <p> * The sequencing operations are performed in the default ExecutionContext. * * @param promises The promises to combine * @return A single promise whose methods act on the list of redeemed promises * Use {@link Futures#sequence(CompletionStage[])} instead. */ public static <A> Promise<List<A>> sequence(Promise<A>... promises) { return wrap(Futures.sequence(Arrays.asList(promises))); }
/** * Create a new promise throwing an exception. * * @param throwable Value to throw * Construct a new {@link CompletableFuture} and use * {@link CompletableFuture#completeExceptionally(Throwable)} instead. */ public static <A> Promise<A> throwing(Throwable throwable) { CompletableFuture<A> future = new CompletableFuture<>(); future.completeExceptionally(throwable); return new Promise<>(future); }
/** * Create a Promise that is redeemed after a timeout. * * @param message The message to use to redeem the Promise. * @param delay The delay expressed in milliseconds. * Use {@link Futures#timeout(Object, long, TimeUnit)} instead. */ public static <A> Promise<A> timeout(A message, long delay) { return wrap(Futures.timeout(message, delay, TimeUnit.MILLISECONDS)); }
/** * Maps this promise to a promise of type <code>B</code>. The function <code>function</code> is applied as * soon as the promise is redeemed. * * @param function The function to map <code>A</code> to <code>B</code>. * @param ec The ExecutionContext to execute the function in. * @return A wrapped promise that maps the type from <code>A</code> to <code>B</code>. * Use {@link #thenApplyAsync(Function, Executor)} */ public <B> Promise<B> map(final Function<? super A, ? extends B> function, Executor ec) { return new Promise<>(wrapped.thenApplyAsync(function, (ec))); }