com.linecorp.armeria.client.Client Java Examples

The following examples show how to use com.linecorp.armeria.client.Client. 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: GrpcClientUnwrapTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void test() {
    final TestServiceBlockingStub client =
            Clients.builder("gproto+http://127.0.0.1:1/")
                   .decorator(LoggingClient.newDecorator())
                   .decorator(RetryingClient.newDecorator(
                           (ctx, cause) -> CompletableFuture.completedFuture(RetryDecision.noRetry())))
                   .build(TestServiceBlockingStub.class);

    assertThat(Clients.unwrap(client, TestServiceBlockingStub.class)).isSameAs(client);

    assertThat(Clients.unwrap(client, RetryingClient.class)).isInstanceOf(RetryingClient.class);
    assertThat(Clients.unwrap(client, LoggingClient.class)).isInstanceOf(LoggingClient.class);

    // The outermost decorator of the client must be returned,
    // because the search begins from outside to inside.
    // In the current setup, the outermost `Unwrappable` and `Client` are
    // `ArmeriaChannel` and `PooledHttpClient` respectively.
    assertThat(Clients.unwrap(client, Unwrappable.class)).isInstanceOf(ArmeriaChannel.class);
    assertThat(Clients.unwrap(client, Client.class)).isInstanceOf(PooledHttpClient.class);

    assertThat(Clients.unwrap(client, DecodingClient.class)).isNull();
}
 
Example #2
Source File: THttpClientUnwrapTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void test() {
    final HelloService.Iface client =
            Clients.builder("tbinary+http://127.0.0.1:1/")
                   .decorator(LoggingClient.newDecorator())
                   .rpcDecorator(RetryingRpcClient.newDecorator(
                           RetryRuleWithContent.<RpcResponse>builder().thenNoRetry()))
                   .build(HelloService.Iface.class);

    assertThat(Clients.unwrap(client, HelloService.Iface.class)).isSameAs(client);

    assertThat(Clients.unwrap(client, RetryingRpcClient.class)).isInstanceOf(RetryingRpcClient.class);
    assertThat(Clients.unwrap(client, LoggingClient.class)).isInstanceOf(LoggingClient.class);

    // The outermost decorator of the client must be returned,
    // because the search begins from outside to inside.
    // In the current setup, the outermost `Unwrappable` and `Client` are
    // `THttpClientInvocationHandler` and `RetryingRpcClient` respectively.
    assertThat(Clients.unwrap(client, Unwrappable.class)).isInstanceOf(THttpClientInvocationHandler.class);
    assertThat(Clients.unwrap(client, Client.class)).isInstanceOf(RetryingRpcClient.class);

    assertThat(Clients.unwrap(client, CircuitBreakerRpcClient.class)).isNull();
}
 
Example #3
Source File: AbstractRetryingClient.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new instance that decorates the specified {@link Client}.
 */
private AbstractRetryingClient(Client<I, O> delegate, @Nullable RetryRule retryRule,
                               @Nullable RetryRuleWithContent<O> retryRuleWithContent,
                               int maxTotalAttempts, long responseTimeoutMillisForEachAttempt) {
    super(delegate);
    this.retryRule = retryRule;
    this.retryRuleWithContent = retryRuleWithContent;
    if (retryRuleWithContent != null) {
        fromRetryRuleWithContent = RetryRuleUtil.fromRetryRuleWithContent(retryRuleWithContent);
    } else {
        fromRetryRuleWithContent = null;
    }

    checkArgument(maxTotalAttempts > 0, "maxTotalAttempts: %s (expected: > 0)", maxTotalAttempts);
    this.maxTotalAttempts = maxTotalAttempts;

    checkArgument(responseTimeoutMillisForEachAttempt >= 0,
                  "responseTimeoutMillisForEachAttempt: %s (expected: >= 0)",
                  responseTimeoutMillisForEachAttempt);
    this.responseTimeoutMillisForEachAttempt = responseTimeoutMillisForEachAttempt;
}
 
Example #4
Source File: AbstractConcurrencyLimitingClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance that decorates the specified {@code delegate} to limit the concurrent number of
 * active requests to {@code maxConcurrency}.
 *
 * @param delegate the delegate {@link Client}
 * @param maxConcurrency the maximum number of concurrent active requests. {@code 0} to disable the limit.
 * @param timeout the amount of time until this decorator fails the request if the request was not
 *                delegated to the {@code delegate} before then
 */
protected AbstractConcurrencyLimitingClient(Client<I, O> delegate,
                                            int maxConcurrency, long timeout, TimeUnit unit) {
    super(delegate);

    validateAll(maxConcurrency, timeout, unit);

    if (maxConcurrency == Integer.MAX_VALUE) {
        this.maxConcurrency = 0;
    } else {
        this.maxConcurrency = maxConcurrency;
    }
    timeoutMillis = unit.toMillis(timeout);
}
 
Example #5
Source File: AbstractCircuitBreakerClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance that decorates the specified {@link Client}.
 */
private AbstractCircuitBreakerClient(Client<I, O> delegate, CircuitBreakerMapping mapping,
                                     @Nullable CircuitBreakerRule rule,
                                     @Nullable CircuitBreakerRuleWithContent<O> ruleWithContent) {
    super(delegate);
    this.mapping = requireNonNull(mapping, "mapping");
    this.rule = rule;
    this.ruleWithContent = ruleWithContent;
    if (ruleWithContent != null) {
        fromRuleWithContent = fromCircuitBreakerRuleWithContent(ruleWithContent);
    } else {
        fromRuleWithContent = null;
    }
}
 
Example #6
Source File: AbstractLoggingClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance that logs {@link Request}s and {@link Response}s at the specified
 * {@link LogLevel}.
 */
AbstractLoggingClient(Client<I, O> delegate, LogLevel level) {
    this(delegate,
         null,
         log -> level,
         log -> level,
         Functions.second(),
         Functions.second(),
         Functions.second(),
         Functions.second(),
         Functions.second(),
         Functions.second(),
         Functions.second(),
         Sampler.always());
}
 
Example #7
Source File: AbstractLoggingClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance that logs {@link Request}s and {@link Response}s at the specified
 * {@link LogLevel}s with the specified sanitizers.
 */
AbstractLoggingClient(
        Client<I, O> delegate,
        @Nullable Logger logger,
        Function<? super RequestOnlyLog, LogLevel> requestLogLevelMapper,
        Function<? super RequestLog, LogLevel> responseLogLevelMapper,
        BiFunction<? super RequestContext, ? super HttpHeaders, ?> requestHeadersSanitizer,
        BiFunction<? super RequestContext, Object, ?> requestContentSanitizer,
        BiFunction<? super RequestContext, ? super HttpHeaders, ?> requestTrailersSanitizer,
        BiFunction<? super RequestContext, ? super HttpHeaders, ?> responseHeadersSanitizer,
        BiFunction<? super RequestContext, Object, ?> responseContentSanitizer,
        BiFunction<? super RequestContext, ? super HttpHeaders, ?> responseTrailersSanitizer,
        BiFunction<? super RequestContext, ? super Throwable, ?> responseCauseSanitizer,
        Sampler<? super ClientRequestContext> sampler) {

    super(requireNonNull(delegate, "delegate"));

    this.logger = logger != null ? logger : LoggerFactory.getLogger(getClass());
    this.requestLogLevelMapper = requireNonNull(requestLogLevelMapper, "requestLogLevelMapper");
    this.responseLogLevelMapper = requireNonNull(responseLogLevelMapper, "responseLogLevelMapper");

    this.requestHeadersSanitizer = requireNonNull(requestHeadersSanitizer, "requestHeadersSanitizer");
    this.requestContentSanitizer = requireNonNull(requestContentSanitizer, "requestContentSanitizer");
    this.requestTrailersSanitizer = requireNonNull(requestTrailersSanitizer, "requestTrailersSanitizer");

    this.responseHeadersSanitizer = requireNonNull(responseHeadersSanitizer, "responseHeadersSanitizer");
    this.responseContentSanitizer = requireNonNull(responseContentSanitizer, "responseContentSanitizer");
    this.responseTrailersSanitizer = requireNonNull(responseTrailersSanitizer, "responseTrailersSanitizer");
    this.responseCauseSanitizer = requireNonNull(responseCauseSanitizer, "responseCauseSanitizer");
    this.sampler = requireNonNull(sampler, "sampler");
}
 
Example #8
Source File: AbstractRetryingClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance that decorates the specified {@link Client}.
 */
AbstractRetryingClient(Client<I, O> delegate,
                       RetryRuleWithContent<O> retryRuleWithContent,
                       int maxTotalAttempts, long responseTimeoutMillisForEachAttempt) {
    this(delegate, null, requireNonNull(retryRuleWithContent, "retryRuleWithContent"),
         maxTotalAttempts, responseTimeoutMillisForEachAttempt);
}
 
Example #9
Source File: ClientUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static <I extends Request, O extends Response, U extends Client<I, O>>
O initContextAndExecuteWithFallback(
        U delegate, DefaultClientRequestContext ctx,
        BiFunction<ClientRequestContext, Throwable, O> errorResponseFactory, boolean succeeded)
        throws Exception {

    if (succeeded) {
        return pushAndExecute(delegate, ctx);
    } else {
        final Throwable cause = ctx.log().partial().requestCause();
        assert cause != null;

        // Context initialization has failed, which means:
        // - ctx.log() has been completed with an exception.
        // - ctx.request() has been aborted (if not null).
        // - the decorator chain was not invoked at all.
        // See `init()` and `failEarly()` in `DefaultClientRequestContext`.

        // Call the decorator chain anyway so that the request is seen by the decorators.
        final O res = pushAndExecute(delegate, ctx);

        // We will use the fallback response which is created from the exception
        // raised in ctx.init(), so the response returned can be aborted.
        if (res instanceof StreamMessage) {
            ((StreamMessage<?>) res).abort(cause);
        }

        // No need to call `fail()` because failed by `DefaultRequestContext.init()` already.
        return errorResponseFactory.apply(ctx, cause);
    }
}
 
Example #10
Source File: ClientUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
public static <I extends Request, O extends Response, U extends Client<I, O>>
O executeWithFallback(U delegate, ClientRequestContext ctx,
                      BiFunction<ClientRequestContext, Throwable, O> errorResponseFactory) {

    requireNonNull(delegate, "delegate");
    requireNonNull(ctx, "ctx");
    requireNonNull(errorResponseFactory, "errorResponseFactory");

    try {
        return pushAndExecute(delegate, ctx);
    } catch (Throwable cause) {
        fail(ctx, cause);
        return errorResponseFactory.apply(ctx, cause);
    }
}
 
Example #11
Source File: ClientUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static <I extends Request, O extends Response, U extends Client<I, O>>
O pushAndExecute(U delegate, ClientRequestContext ctx) throws Exception {
    @SuppressWarnings("unchecked")
    final I req = (I) firstNonNull(ctx.request(), ctx.rpcRequest());
    try (SafeCloseable ignored = ctx.push()) {
        return delegate.execute(ctx, req);
    }
}
 
Example #12
Source File: AbstractCircuitBreakerClient.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance that decorates the specified {@link Client}.
 */
AbstractCircuitBreakerClient(Client<I, O> delegate, CircuitBreakerMapping mapping,
                             CircuitBreakerRule rule) {
    this(delegate, mapping, requireNonNull(rule, "rule"), null);
}
 
Example #13
Source File: AbstractCircuitBreakerClient.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance that decorates the specified {@link Client}.
 */
AbstractCircuitBreakerClient(Client<I, O> delegate, CircuitBreakerMapping mapping,
                             CircuitBreakerRuleWithContent<O> ruleWithContent) {
    this(delegate, mapping, null, requireNonNull(ruleWithContent, "ruleWithContent"));
}
 
Example #14
Source File: AbstractMetricCollectingClient.java    From armeria with Apache License 2.0 4 votes vote down vote up
AbstractMetricCollectingClient(Client<I, O> delegate, MeterIdPrefixFunction meterIdPrefixFunction) {
    super(delegate);
    this.meterIdPrefixFunction = requireNonNull(meterIdPrefixFunction, "meterIdPrefixFunction");
}
 
Example #15
Source File: AbstractRetryingClient.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance that decorates the specified {@link Client}.
 */
AbstractRetryingClient(Client<I, O> delegate, RetryRule retryRule,
                       int maxTotalAttempts, long responseTimeoutMillisForEachAttempt) {
    this(delegate, requireNonNull(retryRule, "retryRule"), null,
         maxTotalAttempts, responseTimeoutMillisForEachAttempt);
}
 
Example #16
Source File: AbstractConcurrencyLimitingClient.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new instance that decorates the specified {@code delegate} to limit the concurrent number of
 * active requests to {@code maxConcurrency}, with the default timeout of {@value #DEFAULT_TIMEOUT_MILLIS}
 * milliseconds.
 *
 * @param delegate the delegate {@link Client}
 * @param maxConcurrency the maximum number of concurrent active requests. {@code 0} to disable the limit.
 */
protected AbstractConcurrencyLimitingClient(Client<I, O> delegate, int maxConcurrency) {
    this(delegate, maxConcurrency, DEFAULT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
}