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 anHttpRequest
that will be sent by thisClient
.addHeaders
(Iterable<? extends Map.Entry<? extends CharSequence, ?>> headers) Adds the default HTTP headers for anHttpRequest
that will be sent by thisClient
.Sets theAuthToken
header 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> T
Returns a newly-created gRPC client which implements the specifiedclientType
, based on the properties of this builder.callCredentials
(CallCredentials callCredentials) Sets theCallCredentials
that 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 theGrpcClientStubFactory
that creates a gRPC client stub.compressor
(Compressor compressor) Sets theCompressor
to use when compressing messages.contextCustomizer
(Consumer<? super ClientRequestContext> contextCustomizer) Adds the specifiedClientRequestContext
customizer function so that it customizes the context in the thread that initiated the client call.decompressorRegistry
(DecompressorRegistry registry) Sets theDecompressorRegistry
to 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 theClientFactory
used for creating a client.Enables automatic redirection.followRedirects
(RedirectConfig redirectConfig) Sets theRedirectConfig
to enable automatic redirection.intercept
(ClientInterceptor... interceptors) Adds theClientInterceptor
s to the gRPC client stub.intercept
(Iterable<? extends ClientInterceptor> interceptors) Adds theClientInterceptor
s to the gRPC client stub.jsonMarshallerFactory
(Function<? super ServiceDescriptor, ? extends GrpcJsonMarshaller> jsonMarshallerFactory) Sets the factory that creates aGrpcJsonMarshaller
that 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 specifiedClientOption
and itsvalue
.option
(ClientOptionValue<T> optionValue) Adds the specifiedClientOptionValue
.options
(ClientOptions options) Adds the specifiedClientOptions
.options
(ClientOptionValue<?>... options) Adds the specifiedClientOptionValue
s.options
(Iterable<ClientOptionValue<?>> options) Adds the specifiedClientOptionValue
s.Deprecated.pathPrefix
(String prefix) Sets the context path for the gRPC endpoint.requestAutoAbortDelay
(Duration delay) Sets the amount of time to wait before aborting anHttpRequest
when its correspondingHttpResponse
is complete.requestAutoAbortDelayMillis
(long delayMillis) Sets the amount of time in millis to wait before aborting anHttpRequest
when its correspondingHttpResponse
is complete.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 anHttpRequest
that will be sent by thisClient
.setHeaders
(Iterable<? extends Map.Entry<? extends CharSequence, ?>> headers) Sets the default HTTP headers for anHttpRequest
that will be sent by thisClient
.successFunction
(SuccessFunction successFunction) Sets aSuccessFunction
that 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 theCompressor
to use when compressing messages. If not set,Codec.Identity.NONE
will 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 theDecompressorRegistry
to use when decompressing messages. If not set, will use the default, which supports gzip only. -
callCredentials
Sets theCallCredentials
that 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
RequestContext
instead of being released. AllByteString
in 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
SerializationFormat
isGrpcSerializationFormats.PROTO_WEB_TEXT
. -
jsonMarshallerFactory
public GrpcClientBuilder jsonMarshallerFactory(Function<? super ServiceDescriptor, ? extends GrpcJsonMarshaller> jsonMarshallerFactory) Sets the factory that creates aGrpcJsonMarshaller
that serializes and deserializes request or response messages to and from JSON depending on theSerializationFormat
. The returnedGrpcJsonMarshaller
from 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-
Message
types such asscalapb.GeneratedMessage
withcom.linecorp.armeria.common.scalapb.ScalaPbJsonMarshaller
for 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 theGrpcClientStubFactory
that creates a gRPC client stub. If not specified, Armeria provides built-in factories for the following gRPC client stubs: -
intercept
Adds theClientInterceptor
s to the gRPC client stub. The specified interceptor(s) is/are executed in reverse order. -
intercept
Adds theClientInterceptor
s 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.rpcDecorator
only supports Thrift.- Overrides:
rpcDecorator
in classAbstractClientOptionsBuilder
- Parameters:
decorator
- theFunction
that transforms anRpcClient
to another
-
rpcDecorator
Deprecated.Use eitherdecorator(DecoratingHttpClientFunction)
orintercept(ClientInterceptor...)
instead.Unsupported operation.rpcDecorator
only supports Thrift.- Overrides:
rpcDecorator
in classAbstractClientOptionsBuilder
- Parameters:
decorator
- theDecoratingRpcClientFunction
that 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:AbstractClientOptionsBuilder
Adds the specifiedClientOptions
.- Overrides:
options
in classAbstractClientOptionsBuilder
-
options
Description copied from class:AbstractClientOptionsBuilder
Adds the specifiedClientOptionValue
s.- Overrides:
options
in classAbstractClientOptionsBuilder
-
options
Description copied from class:AbstractClientOptionsBuilder
Adds the specifiedClientOptionValue
s.- Overrides:
options
in classAbstractClientOptionsBuilder
-
option
Description copied from class:AbstractClientOptionsBuilder
Adds the specifiedClientOption
and itsvalue
.- Overrides:
option
in classAbstractClientOptionsBuilder
-
option
Description copied from class:AbstractClientOptionsBuilder
Adds the specifiedClientOptionValue
.- Overrides:
option
in classAbstractClientOptionsBuilder
-
factory
Description copied from class:AbstractClientOptionsBuilder
Sets theClientFactory
used for creating a client. The default isClientFactory.ofDefault()
.- Overrides:
factory
in classAbstractClientOptionsBuilder
-
writeTimeout
Description copied from class:AbstractClientOptionsBuilder
Sets the timeout of a socket write attempt.- Overrides:
writeTimeout
in classAbstractClientOptionsBuilder
- Parameters:
writeTimeout
- the timeout.0
disables the timeout.
-
writeTimeoutMillis
Description copied from class:AbstractClientOptionsBuilder
Sets the timeout of a socket write attempt in milliseconds.- Overrides:
writeTimeoutMillis
in classAbstractClientOptionsBuilder
- Parameters:
writeTimeoutMillis
- the timeout in milliseconds.0
disables the timeout.
-
responseTimeout
Description copied from class:AbstractClientOptionsBuilder
Sets the timeout of a response.- Overrides:
responseTimeout
in classAbstractClientOptionsBuilder
- Parameters:
responseTimeout
- the timeout.0
disables the timeout.
-
responseTimeoutMillis
Description copied from class:AbstractClientOptionsBuilder
Sets the timeout of a response in milliseconds.- Overrides:
responseTimeoutMillis
in classAbstractClientOptionsBuilder
- Parameters:
responseTimeoutMillis
- the timeout in milliseconds.0
disables the timeout.
-
maxResponseLength
Description copied from class:AbstractClientOptionsBuilder
Sets the maximum allowed length of a server response in bytes.- Overrides:
maxResponseLength
in classAbstractClientOptionsBuilder
- Parameters:
maxResponseLength
- the maximum length in bytes.0
disables the limit.
-
requestAutoAbortDelay
Description copied from class:AbstractClientOptionsBuilder
Sets the amount of time to wait before aborting anHttpRequest
when its correspondingHttpResponse
is complete. This may be useful when you want to send additional data even after the response is complete. SpecifyDuration.ZERO
to abort theHttpRequest
immediately. Any negative value will not abort the request automatically. There is no delay by default.- Overrides:
requestAutoAbortDelay
in classAbstractClientOptionsBuilder
-
requestAutoAbortDelayMillis
Description copied from class:AbstractClientOptionsBuilder
Sets the amount of time in millis to wait before aborting anHttpRequest
when its correspondingHttpResponse
is complete. This may be useful when you want to send additional data even after the response is complete. Specify0
to abort theHttpRequest
immediately. Any negative value will not abort the request automatically. There is no delay by default.- Overrides:
requestAutoAbortDelayMillis
in classAbstractClientOptionsBuilder
-
requestIdGenerator
Description copied from class:AbstractClientOptionsBuilder
- Overrides:
requestIdGenerator
in classAbstractClientOptionsBuilder
-
successFunction
Description copied from class:AbstractClientOptionsBuilder
Sets aSuccessFunction
that determines whether a request was handled successfully or not. If unspecified,SuccessFunction.ofDefault()
is used.- Overrides:
successFunction
in classAbstractClientOptionsBuilder
-
endpointRemapper
public GrpcClientBuilder endpointRemapper(Function<? super Endpoint, ? extends EndpointGroup> endpointRemapper) Description copied from class:AbstractClientOptionsBuilder
Sets aFunction
that remaps anEndpoint
into anEndpointGroup
. ThisClientOption
is 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:
endpointRemapper
in classAbstractClientOptionsBuilder
- See Also:
-
decorator
Description copied from class:AbstractClientOptionsBuilder
Adds the specified HTTP-leveldecorator
.- Overrides:
decorator
in classAbstractClientOptionsBuilder
- Parameters:
decorator
- theFunction
that transforms anHttpClient
to another
-
decorator
Description copied from class:AbstractClientOptionsBuilder
Adds the specified HTTP-leveldecorator
.- Overrides:
decorator
in classAbstractClientOptionsBuilder
- Parameters:
decorator
- theDecoratingHttpClientFunction
that intercepts an invocation
-
clearDecorators
Description copied from class:AbstractClientOptionsBuilder
Clears all HTTP-level and RPC-level decorators set so far.- Overrides:
clearDecorators
in classAbstractClientOptionsBuilder
-
addHeader
Description copied from class:AbstractClientOptionsBuilder
Adds the default HTTP header for anHttpRequest
that will be sent by thisClient
.Note that the values of the default HTTP headers could be overridden if the same
HttpHeaderNames
are defined in theHttpRequest.headers()
orClientRequestContext.additionalRequestHeaders()
.- Overrides:
addHeader
in classAbstractClientOptionsBuilder
-
addHeaders
public GrpcClientBuilder addHeaders(Iterable<? extends Map.Entry<? extends CharSequence, ?>> headers) Description copied from class:AbstractClientOptionsBuilder
Adds the default HTTP headers for anHttpRequest
that will be sent by thisClient
.Note that the values of the default HTTP headers could be overridden if the same
HttpHeaderNames
are defined in theHttpRequest.headers()
orClientRequestContext.additionalRequestHeaders()
.- Overrides:
addHeaders
in classAbstractClientOptionsBuilder
-
setHeader
Description copied from class:AbstractClientOptionsBuilder
Sets the default HTTP header for anHttpRequest
that will be sent by thisClient
.Note that the default HTTP header could be overridden if the same
HttpHeaderNames
are defined inHttpRequest.headers()
orClientRequestContext.additionalRequestHeaders()
.- Overrides:
setHeader
in classAbstractClientOptionsBuilder
-
setHeaders
public GrpcClientBuilder setHeaders(Iterable<? extends Map.Entry<? extends CharSequence, ?>> headers) Description copied from class:AbstractClientOptionsBuilder
Sets the default HTTP headers for anHttpRequest
that will be sent by thisClient
.Note that the values of the default HTTP headers could be overridden if the same
HttpHeaderNames
are defined inHttpRequest.headers()
orClientRequestContext.additionalRequestHeaders()
.- Overrides:
setHeaders
in classAbstractClientOptionsBuilder
-
auth
Description copied from class:AbstractClientOptionsBuilder
Sets the HTTP basic access authentication header usingHttpHeaderNames.AUTHORIZATION
.- Overrides:
auth
in classAbstractClientOptionsBuilder
-
auth
Description copied from class:AbstractClientOptionsBuilder
Sets the OAuth Core 1.0 Revision A header usingHttpHeaderNames.AUTHORIZATION
.- Overrides:
auth
in classAbstractClientOptionsBuilder
-
auth
Description copied from class:AbstractClientOptionsBuilder
Sets the OAuth 2.0 header usingHttpHeaderNames.AUTHORIZATION
.- Overrides:
auth
in classAbstractClientOptionsBuilder
-
auth
Description copied from class:AbstractClientOptionsBuilder
Sets theAuthToken
header usingHttpHeaderNames.AUTHORIZATION
.- Overrides:
auth
in classAbstractClientOptionsBuilder
-
followRedirects
Description copied from class:AbstractClientOptionsBuilder
Enables automatic redirection.- Overrides:
followRedirects
in classAbstractClientOptionsBuilder
-
followRedirects
Description copied from class:AbstractClientOptionsBuilder
Sets theRedirectConfig
to enable automatic redirection.- Overrides:
followRedirects
in classAbstractClientOptionsBuilder
-
contextCustomizer
public GrpcClientBuilder contextCustomizer(Consumer<? super ClientRequestContext> contextCustomizer) Description copied from class:AbstractClientOptionsBuilder
Adds the specifiedClientRequestContext
customizer 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:null
while the customizer function runs, because the target host of theRequest
is not determined yet.- Overrides:
contextCustomizer
in classAbstractClientOptionsBuilder
- See Also:
-
pathPrefix(String)
instead.