Class GrpcClientBuilder
URI using the builder pattern.
Use the factory methods in GrpcClients if you do not have many options to override.-
Method Summary
Modifier and TypeMethodDescriptionaddHeader(CharSequence name, Object value) Adds the default HTTP header for anHttpRequestthat will be sent by thisClient.addHeaders(Iterable<? extends Map.Entry<? extends CharSequence, ?>> headers) Adds the default HTTP headers for anHttpRequestthat will be sent by thisClient.Sets theAuthTokenheader usingHttpHeaderNames.AUTHORIZATION.auth(BasicToken token) Sets the HTTP basic access authentication header usingHttpHeaderNames.AUTHORIZATION.auth(OAuth1aToken token) Sets the OAuth Core 1.0 Revision A header usingHttpHeaderNames.AUTHORIZATION.auth(OAuth2Token token) Sets the OAuth 2.0 header usingHttpHeaderNames.AUTHORIZATION.<T> TReturns a newly-created gRPC client which implements the specifiedclientType, based on the properties of this builder.callCredentials(CallCredentials callCredentials) Sets theCallCredentialsthat carries credential data that will be propagated to the server via request metadata.Clears all HTTP-level and RPC-level decorators set so far.clientStubFactory(GrpcClientStubFactory clientStubFactory) Sets theGrpcClientStubFactorythat creates a gRPC client stub.compressor(Compressor compressor) Sets theCompressorto use when compressing messages.contextCustomizer(Consumer<? super ClientRequestContext> contextCustomizer) Adds the specifiedClientRequestContextcustomizer function so that it customizes the context in the thread that initiated the client call.decompressorRegistry(DecompressorRegistry registry) Sets theDecompressorRegistryto use when decompressing messages.decorator(DecoratingHttpClientFunction decorator) Adds the specified HTTP-leveldecorator.decorator(Function<? super HttpClient, ? extends HttpClient> decorator) Adds the specified HTTP-leveldecorator.enableUnsafeWrapResponseBuffers(boolean enableUnsafeWrapResponseBuffers) (Advanced users only) Enables unsafe retention of response buffers.endpointRemapper(Function<? super Endpoint, ? extends EndpointGroup> endpointRemapper) factory(ClientFactory factory) Sets theClientFactoryused for creating a client.Enables automatic redirection.followRedirects(RedirectConfig redirectConfig) Sets theRedirectConfigto enable automatic redirection.intercept(ClientInterceptor... interceptors) Adds theClientInterceptors to the gRPC client stub.intercept(Iterable<? extends ClientInterceptor> interceptors) Adds theClientInterceptors to the gRPC client stub.jsonMarshallerFactory(Function<? super ServiceDescriptor, ? extends GrpcJsonMarshaller> jsonMarshallerFactory) Sets the factory that creates aGrpcJsonMarshallerthat serializes and deserializes request or response messages to and from JSON depending on theSerializationFormat.maxRequestMessageLength(int maxRequestMessageLength) Sets the maximum size, in bytes, of messages sent in a request.maxResponseLength(long maxResponseLength) Sets the maximum allowed length of a server response in bytes.maxResponseMessageLength(int maxResponseMessageLength) Sets the maximum size, in bytes, of messages coming in a response.option(ClientOption<T> option, T value) Adds the specifiedClientOptionand itsvalue.option(ClientOptionValue<T> optionValue) Adds the specifiedClientOptionValue.options(ClientOptions options) Adds the specifiedClientOptions.options(ClientOptionValue<?>... options) Adds the specifiedClientOptionValues.options(Iterable<ClientOptionValue<?>> options) Adds the specifiedClientOptionValues.Deprecated.pathPrefix(String prefix) Sets the context path for the gRPC endpoint.requestIdGenerator(Supplier<RequestId> requestIdGenerator) responseTimeout(Duration responseTimeout) Sets the timeout of a response.responseTimeoutMillis(long responseTimeoutMillis) Sets the timeout of a response in milliseconds.rpcDecorator(DecoratingRpcClientFunction decorator) Deprecated.Use eitherdecorator(DecoratingHttpClientFunction)orintercept(ClientInterceptor...)instead.rpcDecorator(Function<? super RpcClient, ? extends RpcClient> decorator) Deprecated.Use eitherdecorator(DecoratingHttpClientFunction)orintercept(ClientInterceptor...)instead.serializationFormat(SerializationFormat serializationFormat) Sets the gRPCSerializationFormat.setHeader(CharSequence name, Object value) Sets the default HTTP header for anHttpRequestthat will be sent by thisClient.setHeaders(Iterable<? extends Map.Entry<? extends CharSequence, ?>> headers) Sets the default HTTP headers for anHttpRequestthat will be sent by thisClient.successFunction(SuccessFunction successFunction) Sets aSuccessFunctionthat determines whether a request was handled successfully or not.writeTimeout(Duration writeTimeout) Sets the timeout of a socket write attempt.writeTimeoutMillis(long writeTimeoutMillis) Sets the timeout of a socket write attempt in milliseconds.Methods inherited from class com.linecorp.armeria.client.AbstractClientOptionsBuilder
buildOptions, buildOptions
-
Method Details
-
serializationFormat
Sets the gRPCSerializationFormat. If not set, theScheme.serializationFormat()specified when creating this builder will be used by default.- See Also:
-
path
Deprecated.UsepathPrefix(String)instead.Sets the context path for the gRPC endpoint. This method will be useful if your gRPC service is bound to a context path. For example:// A gRPC service is bound to "/grpc/com.example.MyGrpcService/" Server.builder() .serviceUnder("/grpc", GrpcService.builder() .addService(new MyGrpcService()) .build()) .build(); // Prefix "/grpc" to the gRPC service path. GrpcClient.builder("https://api.example.com") .path("/grpc") .build(MyGrpcServiceGrpc.XXXStub.class) -
pathPrefix
Sets the context path for the gRPC endpoint. This method will be useful if your gRPC service is bound to a context path. For example:// A gRPC service is bound to "/grpc/com.example.MyGrpcService/" Server.builder() .serviceUnder("/grpc", GrpcService.builder() .addService(new MyGrpcService()) .build()) .build(); // Prefix "/grpc" to the gRPC service path. GrpcClient.builder("https://api.example.com") .pathPrefix("/grpc") .build(MyGrpcServiceGrpc.XXXStub.class) -
maxRequestMessageLength
Sets the maximum size, in bytes, of messages sent in a request. The default value is -1, which means unlimited. -
maxResponseMessageLength
Sets the maximum size, in bytes, of messages coming in a response. The default value is -1, which means 'useClientOptions.MAX_RESPONSE_LENGTH'. -
compressor
Sets theCompressorto use when compressing messages. If not set,Codec.Identity.NONEwill be used by default.Note that it is only safe to call this if the server supports the compression format chosen. There is no negotiation performed; if the server does not support the compression chosen, the call will fail.
-
decompressorRegistry
Sets theDecompressorRegistryto use when decompressing messages. If not set, will use the default, which supports gzip only. -
callCredentials
Sets theCallCredentialsthat carries credential data that will be propagated to the server via request metadata. -
enableUnsafeWrapResponseBuffers
@UnstableApi public GrpcClientBuilder enableUnsafeWrapResponseBuffers(boolean enableUnsafeWrapResponseBuffers) (Advanced users only) Enables unsafe retention of response buffers. Can improve performance when working with very large (i.e., several megabytes) payloads.DISCLAIMER: Do not use this if you don't know what you are doing. It is very easy to introduce memory leaks when using this method. You will probably spend much time debugging memory leaks during development if this is enabled. You will probably spend much time debugging memory leaks in production if this is enabled. You probably don't want to do this and should turn back now.
When enabled, the reference-counted buffer received from the server will be stored into
RequestContextinstead of being released. AllByteStringin a protobuf message will reference sections of this buffer instead of having their own copies. When done with a response message, callGrpcUnsafeBufferUtil.releaseBuffer(Object, RequestContext)with the message and the request's context to release the buffer. The message must be the same reference as what was passed to the client stub - a message with the same contents will not work. IfGrpcUnsafeBufferUtil.releaseBuffer(Object, RequestContext)is not called, the memory will be leaked.Note that this has no effect if the payloads are compressed or the
SerializationFormatisGrpcSerializationFormats.PROTO_WEB_TEXT. -
jsonMarshallerFactory
public GrpcClientBuilder jsonMarshallerFactory(Function<? super ServiceDescriptor, ? extends GrpcJsonMarshaller> jsonMarshallerFactory) Sets the factory that creates aGrpcJsonMarshallerthat serializes and deserializes request or response messages to and from JSON depending on theSerializationFormat. The returnedGrpcJsonMarshallerfrom the factory replaces the built-inGrpcJsonMarshaller.This is commonly used to:
- Switch from the default of using lowerCamelCase for field names to using the field name from
the proto definition, by setting
MessageMarshaller.Builder.preservingProtoFieldNames(boolean)viaGrpcJsonMarshallerBuilder.jsonMarshallerCustomizer(Consumer).GrpcClients.builder(grpcServerUri) .jsonMarshallerFactory(serviceDescriptor -> { return GrpcJsonMarshaller.builder() .jsonMarshallerCustomizer(builder -> { builder.preservingProtoFieldNames(true); }) .build(serviceDescriptor); }) .build(); - Set a customer marshaller for non-
Messagetypes such asscalapb.GeneratedMessagewithcom.linecorp.armeria.common.scalapb.ScalaPbJsonMarshallerfor Scala.GrpcClients.builder(grpcServerUri) .jsonMarshallerFactory(_ => ScalaPbJsonMarshaller()) .build()
- Switch from the default of using lowerCamelCase for field names to using the field name from
the proto definition, by setting
-
clientStubFactory
Sets theGrpcClientStubFactorythat creates a gRPC client stub. If not specified, Armeria provides built-in factories for the following gRPC client stubs: -
intercept
Adds theClientInterceptors to the gRPC client stub. The specified interceptor(s) is/are executed in reverse order. -
intercept
Adds theClientInterceptors to the gRPC client stub. The specified interceptor(s) is/are executed in reverse order. -
rpcDecorator
@Deprecated public GrpcClientBuilder rpcDecorator(Function<? super RpcClient, ? extends RpcClient> decorator) Deprecated.Use eitherdecorator(DecoratingHttpClientFunction)orintercept(ClientInterceptor...)instead.Unsupported operation.rpcDecoratoronly supports Thrift.- Overrides:
rpcDecoratorin classAbstractClientOptionsBuilder- Parameters:
decorator- theFunctionthat transforms anRpcClientto another
-
rpcDecorator
Deprecated.Use eitherdecorator(DecoratingHttpClientFunction)orintercept(ClientInterceptor...)instead.Unsupported operation.rpcDecoratoronly supports Thrift.- Overrides:
rpcDecoratorin classAbstractClientOptionsBuilder- Parameters:
decorator- theDecoratingRpcClientFunctionthat intercepts an invocation
-
build
Returns a newly-created gRPC client which implements the specifiedclientType, based on the properties of this builder. -
options
Description copied from class:AbstractClientOptionsBuilderAdds the specifiedClientOptions.- Overrides:
optionsin classAbstractClientOptionsBuilder
-
options
Description copied from class:AbstractClientOptionsBuilderAdds the specifiedClientOptionValues.- Overrides:
optionsin classAbstractClientOptionsBuilder
-
options
Description copied from class:AbstractClientOptionsBuilderAdds the specifiedClientOptionValues.- Overrides:
optionsin classAbstractClientOptionsBuilder
-
option
Description copied from class:AbstractClientOptionsBuilderAdds the specifiedClientOptionand itsvalue.- Overrides:
optionin classAbstractClientOptionsBuilder
-
option
Description copied from class:AbstractClientOptionsBuilderAdds the specifiedClientOptionValue.- Overrides:
optionin classAbstractClientOptionsBuilder
-
factory
Description copied from class:AbstractClientOptionsBuilderSets theClientFactoryused for creating a client. The default isClientFactory.ofDefault().- Overrides:
factoryin classAbstractClientOptionsBuilder
-
writeTimeout
Description copied from class:AbstractClientOptionsBuilderSets the timeout of a socket write attempt.- Overrides:
writeTimeoutin classAbstractClientOptionsBuilder- Parameters:
writeTimeout- the timeout.0disables the timeout.
-
writeTimeoutMillis
Description copied from class:AbstractClientOptionsBuilderSets the timeout of a socket write attempt in milliseconds.- Overrides:
writeTimeoutMillisin classAbstractClientOptionsBuilder- Parameters:
writeTimeoutMillis- the timeout in milliseconds.0disables the timeout.
-
responseTimeout
Description copied from class:AbstractClientOptionsBuilderSets the timeout of a response.- Overrides:
responseTimeoutin classAbstractClientOptionsBuilder- Parameters:
responseTimeout- the timeout.0disables the timeout.
-
responseTimeoutMillis
Description copied from class:AbstractClientOptionsBuilderSets the timeout of a response in milliseconds.- Overrides:
responseTimeoutMillisin classAbstractClientOptionsBuilder- Parameters:
responseTimeoutMillis- the timeout in milliseconds.0disables the timeout.
-
maxResponseLength
Description copied from class:AbstractClientOptionsBuilderSets the maximum allowed length of a server response in bytes.- Overrides:
maxResponseLengthin classAbstractClientOptionsBuilder- Parameters:
maxResponseLength- the maximum length in bytes.0disables the limit.
-
requestIdGenerator
Description copied from class:AbstractClientOptionsBuilder- Overrides:
requestIdGeneratorin classAbstractClientOptionsBuilder
-
successFunction
Description copied from class:AbstractClientOptionsBuilderSets aSuccessFunctionthat determines whether a request was handled successfully or not. If unspecified,SuccessFunction.ofDefault()is used.- Overrides:
successFunctionin classAbstractClientOptionsBuilder
-
endpointRemapper
public GrpcClientBuilder endpointRemapper(Function<? super Endpoint, ? extends EndpointGroup> endpointRemapper) Description copied from class:AbstractClientOptionsBuilderSets aFunctionthat remaps anEndpointinto anEndpointGroup. ThisClientOptionis useful when you need to override a single target host into a group of hosts to enable client-side load-balancing, e.g.MyService.Iface client = Clients.newClient("tbinary+http://example.com/api", MyService.Iface.class); EndpointGroup myGroup = EndpointGroup.of(Endpoint.of("node-1.example.com")), Endpoint.of("node-2.example.com"))); MyService.Iface derivedClient = Clients.newDerivedClient(client, options -> { return options.toBuilder() .endpointRemapper(endpoint -> { if (endpoint.host().equals("example.com")) { return myGroup; } else { return endpoint; } }) .build(); }); // This request goes to 'node-1.example.com' or 'node-2.example.com'. derivedClient.call();Note that the remapping does not occur recursively but only once.
- Overrides:
endpointRemapperin classAbstractClientOptionsBuilder- See Also:
-
decorator
Description copied from class:AbstractClientOptionsBuilderAdds the specified HTTP-leveldecorator.- Overrides:
decoratorin classAbstractClientOptionsBuilder- Parameters:
decorator- theFunctionthat transforms anHttpClientto another
-
decorator
Description copied from class:AbstractClientOptionsBuilderAdds the specified HTTP-leveldecorator.- Overrides:
decoratorin classAbstractClientOptionsBuilder- Parameters:
decorator- theDecoratingHttpClientFunctionthat intercepts an invocation
-
clearDecorators
Description copied from class:AbstractClientOptionsBuilderClears all HTTP-level and RPC-level decorators set so far.- Overrides:
clearDecoratorsin classAbstractClientOptionsBuilder
-
addHeader
Description copied from class:AbstractClientOptionsBuilderAdds the default HTTP header for anHttpRequestthat will be sent by thisClient.Note that the values of the default HTTP headers could be overridden if the same
HttpHeaderNamesare defined in theHttpRequest.headers()orClientRequestContext.additionalRequestHeaders().- Overrides:
addHeaderin classAbstractClientOptionsBuilder
-
addHeaders
public GrpcClientBuilder addHeaders(Iterable<? extends Map.Entry<? extends CharSequence, ?>> headers) Description copied from class:AbstractClientOptionsBuilderAdds the default HTTP headers for anHttpRequestthat will be sent by thisClient.Note that the values of the default HTTP headers could be overridden if the same
HttpHeaderNamesare defined in theHttpRequest.headers()orClientRequestContext.additionalRequestHeaders().- Overrides:
addHeadersin classAbstractClientOptionsBuilder
-
setHeader
Description copied from class:AbstractClientOptionsBuilderSets the default HTTP header for anHttpRequestthat will be sent by thisClient.Note that the default HTTP header could be overridden if the same
HttpHeaderNamesare defined inHttpRequest.headers()orClientRequestContext.additionalRequestHeaders().- Overrides:
setHeaderin classAbstractClientOptionsBuilder
-
setHeaders
public GrpcClientBuilder setHeaders(Iterable<? extends Map.Entry<? extends CharSequence, ?>> headers) Description copied from class:AbstractClientOptionsBuilderSets the default HTTP headers for anHttpRequestthat will be sent by thisClient.Note that the values of the default HTTP headers could be overridden if the same
HttpHeaderNamesare defined inHttpRequest.headers()orClientRequestContext.additionalRequestHeaders().- Overrides:
setHeadersin classAbstractClientOptionsBuilder
-
auth
Description copied from class:AbstractClientOptionsBuilderSets the HTTP basic access authentication header usingHttpHeaderNames.AUTHORIZATION.- Overrides:
authin classAbstractClientOptionsBuilder
-
auth
Description copied from class:AbstractClientOptionsBuilderSets the OAuth Core 1.0 Revision A header usingHttpHeaderNames.AUTHORIZATION.- Overrides:
authin classAbstractClientOptionsBuilder
-
auth
Description copied from class:AbstractClientOptionsBuilderSets the OAuth 2.0 header usingHttpHeaderNames.AUTHORIZATION.- Overrides:
authin classAbstractClientOptionsBuilder
-
auth
Description copied from class:AbstractClientOptionsBuilderSets theAuthTokenheader usingHttpHeaderNames.AUTHORIZATION.- Overrides:
authin classAbstractClientOptionsBuilder
-
followRedirects
Description copied from class:AbstractClientOptionsBuilderEnables automatic redirection.- Overrides:
followRedirectsin classAbstractClientOptionsBuilder
-
followRedirects
Description copied from class:AbstractClientOptionsBuilderSets theRedirectConfigto enable automatic redirection.- Overrides:
followRedirectsin classAbstractClientOptionsBuilder
-
contextCustomizer
public GrpcClientBuilder contextCustomizer(Consumer<? super ClientRequestContext> contextCustomizer) Description copied from class:AbstractClientOptionsBuilderAdds the specifiedClientRequestContextcustomizer function so that it customizes the context in the thread that initiated the client call. The given customizer function is evaluated before the customizer function specified byClients.withContextCustomizer(Consumer).static final ThreadLocal<String> USER_ID = new ThreadLocal<>(); static final AttributeKey<String> USER_ID_ATTR = AttributeKey.valueOf("USER_ID"); ... MyClientStub client = Clients.builder(...) .contextCustomizer(ctx -> { // This customizer will be invoked from the thread that initiates a client call. ctx.setAttr(USER_ID_ATTR, USER_ID.get()); }) .build(MyClientStub.class); // Good: // The context data is set by the thread that initiates the client call. USER_ID.set("user1"); try { client.executeSomething1(..); ... client.executeSomethingN(..); } finally { // Should clean up the thread local storage. USER_ID.remove(); } // Bad: USER_ID.set("user1"); executor.execute(() -> { // The variable in USER_ID won't be propagated to the context. // The variable is not valid at the moment client.executeSomething1() is called. client.executeSomething1(..); });Note that certain properties of
may beClientRequestContext, such as:nullwhile the customizer function runs, because the target host of theRequestis not determined yet.- Overrides:
contextCustomizerin classAbstractClientOptionsBuilder- See Also:
-
pathPrefix(String)instead.