Class GrpcServiceBuilder
GrpcService to serve gRPC services from within Armeria.-
Method Summary
Modifier and TypeMethodDescriptionaddExceptionMapping(Class<? extends Throwable> exceptionType, GrpcStatusFunction statusFunction) Deprecated.addExceptionMapping(Class<? extends Throwable> exceptionType, io.grpc.Status status) Deprecated.<T extends Throwable>
GrpcServiceBuilderaddExceptionMapping(Class<T> exceptionType, BiFunction<T, io.grpc.Metadata, io.grpc.Status> statusFunction) Deprecated.addService(io.grpc.BindableService bindableService) Adds a gRPCBindableServiceto thisGrpcServiceBuilder.addService(io.grpc.BindableService bindableService, Iterable<? extends Function<? super HttpService, ? extends HttpService>> decorators) Decorates a gRPCBindableServicewith the given decorators, in the order of iteration.addService(io.grpc.ServerServiceDefinition service) Adds a gRPCServerServiceDefinitionto thisGrpcServiceBuilder, such as what's returned byBindableService.bindService().addService(String path, io.grpc.BindableService bindableService) Adds a gRPCBindableServiceto thisGrpcServiceBuilder.addService(String path, io.grpc.BindableService bindableService, io.grpc.MethodDescriptor<?, ?> methodDescriptor) Adds a method of gRPCBindableServiceto thisGrpcServiceBuilder.addService(String path, io.grpc.BindableService bindableService, io.grpc.MethodDescriptor<?, ?> methodDescriptor, Iterable<? extends Function<? super HttpService, ? extends HttpService>> decorators) Decorates a method of gRPCBindableServicewith the given decorators, in the order of iteration.addService(String path, io.grpc.BindableService bindableService, Iterable<? extends Function<? super HttpService, ? extends HttpService>> decorators) Decorates a gRPCBindableServicewith the given decorators, in the order of iteration.addService(String path, io.grpc.ServerServiceDefinition service) Adds a gRPCServerServiceDefinitionto thisGrpcServiceBuilder, such as what's returned byBindableService.bindService().addService(String path, io.grpc.ServerServiceDefinition service, io.grpc.MethodDescriptor<?, ?> methodDescriptor) Adds a method of gRPCServerServiceDefinitionto thisGrpcServiceBuilder.addService(T implementation, Function<? super T, io.grpc.ServerServiceDefinition> serviceDefinitionFactory) Adds an implementation of gRPC service to thisGrpcServiceBuilder.addService(T implementation, Function<? super T, io.grpc.ServerServiceDefinition> serviceDefinitionFactory, Iterable<? extends Function<? super HttpService, ? extends HttpService>> decorators) Decorates an implementation of gRPC service with the given decorators, in the order of iteration.addServiceDefinitions(io.grpc.ServerServiceDefinition... services) Adds gRPCServerServiceDefinitions to thisGrpcServiceBuilder.addServiceDefinitions(Iterable<io.grpc.ServerServiceDefinition> services) Adds gRPCServerServiceDefinitions to thisGrpcServiceBuilder.addServices(io.grpc.BindableService... bindableServices) Adds gRPCBindableServices to thisGrpcServiceBuilder.addServices(Iterable<io.grpc.BindableService> bindableServices) Adds gRPCBindableServices to thisGrpcServiceBuilder.autoCompression(boolean autoCompression) Sets whether the gRPC response is compressed automatically when a client sends thegrpc-accept-encodingheader with the encoding registered in theCompressorRegistry.build()Constructs a newGrpcServicethat can be bound toServerBuilder.compressorRegistry(io.grpc.CompressorRegistry registry) Sets theCompressorRegistryto use when compressing messages.decompressorRegistry(io.grpc.DecompressorRegistry registry) Sets theDecompressorRegistryto use when decompressing messages.enableHealthCheckService(boolean enableHealthCheckService) Sets the defaultGrpcHealthCheckServiceto thisGrpcServiceBuilder.enableHttpJsonTranscoding(boolean enableHttpJsonTranscoding) Sets whether the service handles HTTP/JSON requests using the gRPC wire protocol.enableHttpJsonTranscoding(HttpJsonTranscodingOptions httpJsonTranscodingOptions) Enables HTTP/JSON transcoding using the gRPC wire protocol.enableUnframedRequests(boolean enableUnframedRequests) Sets whether the service handles requests not framed using the gRPC wire protocol.exceptionHandler(GrpcExceptionHandlerFunction exceptionHandler) exceptionMapping(GrpcStatusFunction statusFunction) Deprecated.UseexceptionHandler(GrpcExceptionHandlerFunction)instead.httpJsonTranscodingErrorHandler(UnframedGrpcErrorHandler httpJsonTranscodingErrorHandler) Deprecated.intercept(io.grpc.ServerInterceptor... interceptors) Adds server interceptors into the gRPC service.Adds server interceptors into the gRPC service.jsonMarshallerFactory(Function<? super io.grpc.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 an individual request message.maxResponseMessageLength(int maxResponseMessageLength) Sets the maximum size in bytes of an individual response message.setMaxInboundMessageSizeBytes(int maxInboundMessageSizeBytes) Deprecated.UsemaxRequestMessageLength(int)instead.setMaxOutboundMessageSizeBytes(int maxOutboundMessageSizeBytes) Deprecated.UsemaxResponseMessageLength(int)instead.supportedSerializationFormats(SerializationFormat... formats) Sets theSerializationFormats supported by this server.Sets theSerializationFormats supported by this server.unframedGrpcErrorHandler(UnframedGrpcErrorHandler unframedGrpcErrorHandler) Set a custom error response mapper.unsafeWrapRequestBuffers(boolean unsafeWrapRequestBuffers) Enables unsafe retention of request buffers.useBlockingTaskExecutor(boolean useBlockingTaskExecutor) Sets whether the service executes service methods using the blocking executor.useClientTimeoutHeader(boolean useClientTimeoutHeader) Sets whether to use agrpc-timeoutheader sent by the client to control the timeout for request processing.useMethodMarshaller(boolean useMethodMarshaller) Sets whether to respect the marshaller specified in gRPCMethodDescriptorIf not set, will use the default(false), which use more efficient way that reduce copy operation.
-
Method Details
-
addService
Adds a gRPCServerServiceDefinitionto thisGrpcServiceBuilder, such as what's returned byBindableService.bindService(). -
addService
Adds a gRPCServerServiceDefinitionto thisGrpcServiceBuilder, such as what's returned byBindableService.bindService().Note that the specified
pathreplaces the normal gRPC service path. Let's say you have the following gRPC service definition.
The normal gRPC service path for thepackage example.grpc.hello; service HelloService { rpc Hello (HelloRequest) returns (HelloReply) {} }Hellomethod is"/example.grpc.hello.HelloService/Hello". However, if you set"/foo"topath, theHellomethod will be served at"/foo/Hello". This is useful for supporting unframed gRPC with HTTP idiomatic path. -
addService
public GrpcServiceBuilder addService(String path, io.grpc.ServerServiceDefinition service, io.grpc.MethodDescriptor<?, ?> methodDescriptor) Adds a method of gRPCServerServiceDefinitionto thisGrpcServiceBuilder. You can getMethodDescriptors from the enclosing class of your generated stub.Note that the specified
pathreplaces the normal gRPC service path. Let's say you have the following gRPC service definition.
The normal gRPC service path for thepackage example.grpc.hello; service HelloService { rpc Hello (HelloRequest) returns (HelloReply) {} }Hellomethod is"/example.grpc.hello.HelloService/Hello". However, if you set"/fooHello"topath, theHellomethod will be served at"/fooHello". This is useful for supporting unframed gRPC with HTTP idiomatic path. -
addService
Adds a gRPCBindableServiceto thisGrpcServiceBuilder. Most gRPC service implementations areBindableServices. -
addService
@UnstableApi public GrpcServiceBuilder addService(io.grpc.BindableService bindableService, Iterable<? extends Function<? super HttpService, ? extends HttpService>> decorators) Decorates a gRPCBindableServicewith the given decorators, in the order of iteration. For more details on decorator behavior, please refer to the following document.- See Also:
-
addService
Adds a gRPCBindableServiceto thisGrpcServiceBuilder. Most gRPC service implementations areBindableServices.Note that the specified
pathreplaces the normal gRPC service path. Let's say you have the following gRPC service definition.
The normal gRPC service path for thepackage example.grpc.hello; service HelloService { rpc Hello (HelloRequest) returns (HelloReply) {} }Hellomethod is"/example.grpc.hello.HelloService/Hello". However, if you set"/foo"topath, theHellomethod will be served at"/foo/Hello". This is useful for supporting unframed gRPC with HTTP idiomatic path. -
addService
@UnstableApi public GrpcServiceBuilder addService(String path, io.grpc.BindableService bindableService, Iterable<? extends Function<? super HttpService, ? extends HttpService>> decorators) Decorates a gRPCBindableServicewith the given decorators, in the order of iteration. For more details on decorator behavior, please refer to the following document.- See Also:
-
addService
public <T> GrpcServiceBuilder addService(T implementation, Function<? super T, io.grpc.ServerServiceDefinition> serviceDefinitionFactory) Adds an implementation of gRPC service to thisGrpcServiceBuilder. Most gRPC service implementations areBindableServices. This method is useful in cases like the followings.Used for ScalaPB gRPC stubs
GrpcService.builder() .addService(new HelloServiceImpl, HelloServiceGrpc.bindService(_, ExecutionContext.global))Used for intercepted gRPC-Java stubs
GrpcService.builder() .addService(new TestServiceImpl, impl -> ServerInterceptors.intercept(impl, interceptors)); -
addService
@UnstableApi public <T> GrpcServiceBuilder addService(T implementation, Function<? super T, io.grpc.ServerServiceDefinition> serviceDefinitionFactory, Iterable<? extends Function<? super HttpService, ? extends HttpService>> decorators) Decorates an implementation of gRPC service with the given decorators, in the order of iteration.Most gRPC service implementations are
BindableServices. This method is useful in cases like the followings.Used for ScalaPB gRPC stubs
GrpcService.builder() .addService(new HelloServiceImpl, HelloServiceGrpc.bindService(_, ExecutionContext.global))Used for intercepted gRPC-Java stubs
GrpcService.builder() .addService(new TestServiceImpl, impl -> ServerInterceptors.intercept(impl, interceptors));For more details on decorator behavior, please refer to the following document.
- See Also:
-
addService
public GrpcServiceBuilder addService(String path, io.grpc.BindableService bindableService, io.grpc.MethodDescriptor<?, ?> methodDescriptor) Adds a method of gRPCBindableServiceto thisGrpcServiceBuilder. You can getMethodDescriptors from the enclosing class of your generated stub.Note that the specified
pathreplaces the normal gRPC service path. Let's say you have the following gRPC service definition.
The normal gRPC service path for thepackage example.grpc.hello; service HelloService { rpc Hello (HelloRequest) returns (HelloReply) {} }Hellomethod is"/example.grpc.hello.HelloService/Hello". However, if you set"/fooHello"topath, theHellomethod will be served at"/fooHello". This is useful for supporting unframed gRPC with HTTP idiomatic path. -
addService
@UnstableApi public GrpcServiceBuilder addService(String path, io.grpc.BindableService bindableService, io.grpc.MethodDescriptor<?, ?> methodDescriptor, Iterable<? extends Function<? super HttpService, ? extends HttpService>> decorators) Decorates a method of gRPCBindableServicewith the given decorators, in the order of iteration. For more details on decorator behavior, please refer to the following document.- See Also:
-
intercept
Adds server interceptors into the gRPC service. The last interceptor will have itsServerInterceptor.interceptCall(io.grpc.ServerCall<ReqT, RespT>, io.grpc.Metadata, io.grpc.ServerCallHandler<ReqT, RespT>)called first.- Parameters:
interceptors- array of interceptors to apply to the service.
-
intercept
Adds server interceptors into the gRPC service. The last interceptor will have itsServerInterceptor.interceptCall(io.grpc.ServerCall<ReqT, RespT>, io.grpc.Metadata, io.grpc.ServerCallHandler<ReqT, RespT>)called first.- Parameters:
interceptors- list of interceptors to apply to the service.
-
addServices
Adds gRPCBindableServices to thisGrpcServiceBuilder. Most gRPC service implementations areBindableServices. -
addServices
Adds gRPCBindableServices to thisGrpcServiceBuilder. Most gRPC service implementations areBindableServices. -
addServiceDefinitions
Adds gRPCServerServiceDefinitions to thisGrpcServiceBuilder. -
addServiceDefinitions
Adds gRPCServerServiceDefinitions to thisGrpcServiceBuilder. -
decompressorRegistry
Sets theDecompressorRegistryto use when decompressing messages. If not set, will use the default, which supports gzip only. -
compressorRegistry
Sets theCompressorRegistryto use when compressing messages. If not set, will use the default, which supports gzip only. -
supportedSerializationFormats
Sets theSerializationFormats supported by this server. If not set, defaults to support allGrpcSerializationFormats.values(). -
supportedSerializationFormats
Sets theSerializationFormats supported by this server. If not set, defaults to support allGrpcSerializationFormats.values(). -
setMaxInboundMessageSizeBytes
Deprecated.UsemaxRequestMessageLength(int)instead.Sets the maximum size in bytes of an individual incoming message. If not set, will useVirtualHost.maxRequestLength(). To support long-running RPC streams, it is recommended to setServerBuilder.maxRequestLength(long)(orVirtualHostBuilder.maxRequestLength(long)) andServerBuilder.requestTimeoutMillis(long)(orVirtualHostBuilder.requestTimeoutMillis(long)) to very high values and set this to the expected limit of individual messages in the stream. -
setMaxOutboundMessageSizeBytes
@Deprecated public GrpcServiceBuilder setMaxOutboundMessageSizeBytes(int maxOutboundMessageSizeBytes) Deprecated.UsemaxResponseMessageLength(int)instead.Sets the maximum size in bytes of an individual outgoing message. If not set, all messages will be sent. This can be a safety valve to prevent overflowing network connections with large messages due to business logic bugs. -
maxRequestMessageLength
Sets the maximum size in bytes of an individual request message. If not set, will useVirtualHost.maxRequestLength(). To support long-running RPC streams, it is recommended to setServerBuilder.maxRequestLength(long)(orVirtualHostBuilder.maxRequestLength(long)) andServerBuilder.requestTimeoutMillis(long)(orVirtualHostBuilder.requestTimeoutMillis(long)) to very high values and set this to the expected limit of individual messages in the stream. -
maxResponseMessageLength
Sets the maximum size in bytes of an individual response message. If not set, all messages will be sent. This can be a safety valve to prevent overflowing network connections with large messages due to business logic bugs. -
enableUnframedRequests
Sets whether the service handles requests not framed using the gRPC wire protocol. Such requests should only have the serialized message as the request content, and the response content will only have the serialized response message. Supporting unframed requests can be useful, for example, when migrating an existing service to gRPC.Limitations:
- Only unary methods (single request, single response) are supported.
-
Message compression is not supported.
EncodingServiceshould be used instead for transport level encoding.
-
unframedGrpcErrorHandler
@UnstableApi public GrpcServiceBuilder unframedGrpcErrorHandler(UnframedGrpcErrorHandler unframedGrpcErrorHandler) Set a custom error response mapper. This is useful to serve custom response when using unframed gRPC service.- Parameters:
unframedGrpcErrorHandler- The function which maps the error response to anHttpResponse.
-
enableHttpJsonTranscoding
Sets whether the service handles HTTP/JSON requests using the gRPC wire protocol.Limitations:
- Only unary methods (single request, single response) are supported.
-
Message compression is not supported.
EncodingServiceshould be used instead for transport level encoding. -
Transcoding will not work if the
GrpcServiceis configured withServerBuilder.serviceUnder(String, HttpService).
When custom
supportedSerializationFormats(SerializationFormat...)are used,GrpcSerializationFormats.JSONmust be included to enable HTTP/JSON transcoding. Otherwise, service builder will throwIllegalStateExceptionwhen building the service.- See Also:
-
enableHttpJsonTranscoding
@UnstableApi public GrpcServiceBuilder enableHttpJsonTranscoding(HttpJsonTranscodingOptions httpJsonTranscodingOptions) Enables HTTP/JSON transcoding using the gRPC wire protocol. ProvideHttpJsonTranscodingOptionsto customize HttpJsonTranscoding.Example:
HttpJsonTranscodingOptions options = HttpJsonTranscodingOptions.builder() .queryParamMatchRules(ORIGINAL_FIELD) ... .build(); GrpcService.builder() // Enable HttpJsonTranscoding and use the specified HttpJsonTranscodingOption .enableHttpJsonTranscoding(options) .build();Limitations:
- Only unary methods (single request, single response) are supported.
-
Message compression is not supported.
EncodingServiceshould be used instead for transport level encoding. -
Transcoding will not work if the
GrpcServiceis configured withServerBuilder.serviceUnder(String, HttpService).
- See Also:
-
httpJsonTranscodingErrorHandler
@UnstableApi @Deprecated public GrpcServiceBuilder httpJsonTranscodingErrorHandler(UnframedGrpcErrorHandler httpJsonTranscodingErrorHandler) Deprecated.Sets an error handler which handles an exception raised while serving a gRPC request transcoded from an HTTP/JSON request. By default,UnframedGrpcErrorHandler.ofJson()would be set. -
useBlockingTaskExecutor
Sets whether the service executes service methods using the blocking executor. By default, service methods are executed directly on the event loop for implementing fully asynchronous services. If your service uses blocking logic, you should either execute such logic in a separate thread using something likeExecutors.newCachedThreadPool()or enable this setting. -
unsafeWrapRequestBuffers
Enables unsafe retention of request 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 client 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 request 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 service 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 isn't working if the payloads are compressed or the
SerializationFormatisGrpcSerializationFormats.PROTO_WEB_TEXT. -
jsonMarshallerFactory
public GrpcServiceBuilder jsonMarshallerFactory(Function<? super io.grpc.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).GrpcService.builder() .jsonMarshallerFactory(serviceDescriptor -> { return GrpcJsonMarshaller.builder() .jsonMarshallerCustomizer(builder -> { builder.preservingProtoFieldNames(true); }) .build(serviceDescriptor); }) .build(); - Set a customer marshaller for non-
Messagetypes such asscalapb.GeneratedMessagefor Scala andpbandk.Messagefor Kotlin.
- Switch from the default of using lowerCamelCase for field names to using the field name from
the proto definition, by setting
-
useClientTimeoutHeader
Sets whether to use agrpc-timeoutheader sent by the client to control the timeout for request processing. If disabled, the request timeout will be the one configured for the Armeria server, e.g., usingServerBuilder.requestTimeout(Duration).It is recommended to disable this when clients are not trusted code, e.g., for gRPC-Web clients that can come from arbitrary browsers.
-
enableHealthCheckService
Sets the defaultGrpcHealthCheckServiceto thisGrpcServiceBuilder. The gRPC health check service manages only the health checker that determines the healthiness of theServer.- See Also:
-
autoCompression
Sets whether the gRPC response is compressed automatically when a client sends thegrpc-accept-encodingheader with the encoding registered in theCompressorRegistry. -
useMethodMarshaller
Sets whether to respect the marshaller specified in gRPCMethodDescriptorIf not set, will use the default(false), which use more efficient way that reduce copy operation. -
exceptionHandler
@UnstableApi public GrpcServiceBuilder exceptionHandler(GrpcExceptionHandlerFunction exceptionHandler) Sets the specifiedGrpcExceptionHandlerFunctionthat maps aThrowableto a gRPCStatus.Note that this method and
addExceptionMapping(Class, Status)are mutually exclusive. -
exceptionMapping
Deprecated.UseexceptionHandler(GrpcExceptionHandlerFunction)instead.Sets the specifiedGrpcExceptionHandlerFunctionthat maps aThrowableto a gRPCStatus.Note that this method and
addExceptionMapping(Class, Status)are mutually exclusive. -
addExceptionMapping
@Deprecated public GrpcServiceBuilder addExceptionMapping(Class<? extends Throwable> exceptionType, io.grpc.Status status) Deprecated.Adds the specified exception mapping that maps aThrowableto a gRPCStatus. The mapping is used to handle aThrowablewhen it is raised.Note that this method and
exceptionHandler(GrpcExceptionHandlerFunction)are mutually exclusive. -
addExceptionMapping
@Deprecated public <T extends Throwable> GrpcServiceBuilder addExceptionMapping(Class<T> exceptionType, BiFunction<T, io.grpc.Metadata, io.grpc.Status> statusFunction) Deprecated.Adds the specified exception mapping that maps aThrowableto a gRPCStatus. The mapping is used to handle aThrowablewhen it is raised.Note that this method and
exceptionMapping(GrpcStatusFunction)are mutually exclusive. -
addExceptionMapping
@Deprecated public GrpcServiceBuilder addExceptionMapping(Class<? extends Throwable> exceptionType, GrpcStatusFunction statusFunction) Deprecated.Adds the specified exception mapping that maps aThrowableto a gRPCStatus. The mapping is used to handle aThrowablewhen it is raised.Note that this method and
exceptionMapping(GrpcStatusFunction)are mutually exclusive. -
build
Constructs a newGrpcServicethat can be bound toServerBuilder. It is recommended to bind the service to a server using ServerBuilder.service(HttpServiceWithRoutes) to mount all service paths without interfering with other services.
-
GrpcExceptionHandlerFunctionBuilder.on(Class, GrpcExceptionHandlerFunction)instead.