Class ServerBuilder
- All Implemented Interfaces:
TlsSetters
Server
and its ServerConfig
.
Example
ServerBuilder sb = Server.builder();
// Add a port to listen
sb.http(8080);
// Add services to the default virtual host.
sb.service(...);
sb.serviceUnder(...);
// Build a server.
Server s = sb.build();
Example 2
ServerBuilder sb = Server.builder();
Server server =
sb.http(8080) // Add a port to listen
.defaultVirtualHost() // Add services to the default virtual host.
.service(...)
.serviceUnder(...)
.and().virtualHost("*.foo.com") // Add a another virtual host.
.service(...)
.serviceUnder(...)
.and().build(); // Build a server.
What happens if no HTTP(S) port is specified?
When no TCP/IP port number or local address is specified, ServerBuilder
will automatically bind
to a random TCP/IP port assigned by the OS. It will serve HTTPS if you configured TLS (or HTTP otherwise),
e.g.
// Build an HTTP server that runs on an ephemeral TCP/IP port.
Server httpServer = Server.builder()
.service(...)
.build();
// Build an HTTPS server that runs on an ephemeral TCP/IP port.
Server httpsServer = Server.builder()
.tls(...)
.service(...)
.build();
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionabsoluteUriTransformer
(Function<? super String, String> absoluteUriTransformer) Sets theFunction
that transforms the absolute URI in an HTTP/1 request line into an absolute path.accessLogFormat
(String accessLogFormat) Sets the format of thisServer
's access log.accessLogger
(String loggerName) Sets the default access logger name for allVirtualHost
s.accessLogger
(Function<? super VirtualHost, ? extends Logger> mapper) Sets the default access logger mapper for allVirtualHost
s.accessLogger
(Logger logger) Sets the default accessLogger
for allVirtualHost
s.accessLogWriter
(AccessLogWriter accessLogWriter, boolean shutdownOnStop) Sets an access log writer of thisServer
.addHeader
(CharSequence name, Object value) Adds the default HTTP header for anHttpResponse
served by the defaultVirtualHost
.addHeaders
(Iterable<? extends Map.Entry<? extends CharSequence, ?>> defaultHeaders) Adds the default HTTP headers for anHttpResponse
served by the defaultVirtualHost
.Returns anAnnotatedServiceBindingBuilder
to build annotated service.annotatedService
(Object service) Binds the specified annotated service object under the path prefix"/"
.annotatedService
(Object service, Object... exceptionHandlersAndConverters) Binds the specified annotated service object under the path prefix"/"
.annotatedService
(Object service, Function<? super HttpService, ? extends HttpService> decorator, Object... exceptionHandlersAndConverters) Binds the specified annotated service object under the path prefix"/"
.annotatedService
(String pathPrefix, Object service) Binds the specified annotated service object under the specified path prefix.annotatedService
(String pathPrefix, Object service, Iterable<?> exceptionHandlersAndConverters) Binds the specified annotated service object under the specified path prefix.annotatedService
(String pathPrefix, Object service, Object... exceptionHandlersAndConverters) Binds the specified annotated service object under the specified path prefix.annotatedService
(String pathPrefix, Object service, Function<? super HttpService, ? extends HttpService> decorator, Iterable<?> exceptionHandlersAndConverters) Binds the specified annotated service object under the specified path prefix.annotatedService
(String pathPrefix, Object service, Function<? super HttpService, ? extends HttpService> decorator, Iterable<? extends ExceptionHandlerFunction> exceptionHandlerFunctions, Iterable<? extends RequestConverterFunction> requestConverterFunctions, Iterable<? extends ResponseConverterFunction> responseConverterFunctions) Binds the specified annotated service object under the specified path prefix.annotatedService
(String pathPrefix, Object service, Function<? super HttpService, ? extends HttpService> decorator, Object... exceptionHandlersAndConverters) Binds the specified annotated service object under the specified path prefix.annotatedServiceExtensions
(Iterable<? extends RequestConverterFunction> requestConverterFunctions, Iterable<? extends ResponseConverterFunction> responseConverterFunctions, Iterable<? extends ExceptionHandlerFunction> exceptionHandlerFunctions) Sets theRequestConverterFunction
s,ResponseConverterFunction
andExceptionHandlerFunction
s for creating anAnnotatedServiceExtensions
.baseContextPath
(String baseContextPath) Sets the base context path for thisServerBuilder
.blockingTaskExecutor
(int numThreads) Uses a newly createdBlockingTaskExecutor
with the specified number of threads dedicated to the execution of blocking tasks or invocations.blockingTaskExecutor
(BlockingTaskExecutor blockingTaskExecutor, boolean shutdownOnStop) Sets theBlockingTaskExecutor
dedicated to the execution of blocking tasks or invocations.blockingTaskExecutor
(ScheduledExecutorService blockingTaskExecutor, boolean shutdownOnStop) Sets theScheduledExecutorService
dedicated to the execution of blocking tasks or invocations.build()
Returns a newly-createdServer
based on the configuration properties set so far.<T> ServerBuilder
channelOption
(ChannelOption<T> option, T value) Sets theChannelOption
of the server socket bound byServer
.<T> ServerBuilder
childChannelOption
(ChannelOption<T> option, T value) Sets theChannelOption
of sockets accepted byServer
.childChannelPipelineCustomizer
(Consumer<? super ChannelPipeline> childChannelPipelineCustomizer) (Advanced users only) Adds theConsumer
that customizes the NettyChannelPipeline
.clientAddressFilter
(Predicate<? super InetAddress> clientAddressFilter) Sets a filter which evaluates whether anInetAddress
can be used as a client address.clientAddressMapper
(Function<? super ProxiedAddresses, ? extends InetSocketAddress> clientAddressMapper) Sets aFunction
to use when determining the client address fromProxiedAddresses
.clientAddressSources
(ClientAddressSource... clientAddressSources) Sets a list ofClientAddressSource
s which are used to determine where to look for the client address, in the order of preference.clientAddressSources
(Iterable<ClientAddressSource> clientAddressSources) Sets a list ofClientAddressSource
s which are used to determine where to look for the client address, in the order of preference.clientAddressTrustedProxyFilter
(Predicate<? super InetAddress> clientAddressTrustedProxyFilter) Sets a filter which evaluates whether anInetAddress
of a remote endpoint is trusted.connectionDrainDuration
(Duration duration) Sets the connection drain duration in micros for the connection shutdown.connectionDrainDurationMicros
(long durationMicros) Sets the connection drain duration in micros for the connection shutdown.contextHook
(Supplier<? extends AutoCloseable> contextHook) Sets theAutoCloseable
which will be called whenever thisRequestContext
is popped from theRequestContextStorage
.contextPath
(Iterable<String> contextPaths) Returns aContextPathServicesBuilder
which bindsHttpService
s under the specified context paths.contextPath
(String... contextPaths) Returns aContextPathServicesBuilder
which bindsHttpService
s under the specified context paths.decorator
(DecoratingHttpServiceFunction decoratingHttpServiceFunction) Decorates allHttpService
s with the specifiedDecoratingHttpServiceFunction
.decorator
(Route route, DecoratingHttpServiceFunction decoratingHttpServiceFunction) DecoratesHttpService
s with the specifiedRoute
.decorator
(Route route, Function<? super HttpService, ? extends HttpService> decorator) DecoratesHttpService
s with the specifiedRoute
.decorator
(String pathPattern, DecoratingHttpServiceFunction decoratingHttpServiceFunction) decorator
(String pathPattern, Function<? super HttpService, ? extends HttpService> decorator) decorator
(Function<? super HttpService, ? extends HttpService> decorator) Decorates allHttpService
s with the specifieddecorator
.decoratorUnder
(String prefix, DecoratingHttpServiceFunction decoratingHttpServiceFunction) DecoratesHttpService
s under the specified directory.decoratorUnder
(String prefix, Function<? super HttpService, ? extends HttpService> decorator) DecoratesHttpService
s under the specified directory.defaultHostname
(String defaultHostname) Sets the default hostname of the defaultVirtualHostBuilder
.defaultServiceNaming
(ServiceNaming defaultServiceNaming) Sets a global naming rule for the name of services.Returns theVirtualHostBuilder
for building the default name-based virtual host.dependencyInjector
(DependencyInjector dependencyInjector, boolean shutdownOnStop) Sets theDependencyInjector
to inject dependencies in annotated services.Sets the response header not to include default"Date"
header.Sets the response header not to include default"Server"
header.errorHandler
(ServerErrorHandler errorHandler) Adds theServerErrorHandler
that provides the error responses in case of unexpected exceptions or protocol errors.gracefulShutdownTimeout
(Duration quietPeriod, Duration timeout) Sets the amount of time to wait after callingServer.stop()
for requests to go away before actually shutting down.gracefulShutdownTimeoutMillis
(long quietPeriodMillis, long timeoutMillis) Sets the amount of time to wait after callingServer.stop()
for requests to go away before actually shutting down.http
(int port) Adds an HTTP port that listens on all available network interfaces.http
(InetSocketAddress localAddress) Adds an HTTP port that listens to the specifiedlocalAddress
.http1HeaderNaming
(Http1HeaderNaming http1HeaderNaming) Sets theHttp1HeaderNaming
which converts a lower-cased HTTP/2 header name into another HTTP/1 header name.http1MaxChunkSize
(int http1MaxChunkSize) Sets the maximum length of each chunk in an HTTP/1 response content.http1MaxHeaderSize
(int http1MaxHeaderSize) Sets the maximum length of all headers in an HTTP/1 response.http1MaxInitialLineLength
(int http1MaxInitialLineLength) Sets the maximum length of an HTTP/1 response initial line.http2InitialConnectionWindowSize
(int http2InitialConnectionWindowSize) Sets the initial connection-level HTTP/2 flow control window size.http2InitialStreamWindowSize
(int http2InitialStreamWindowSize) Sets the initial stream-level HTTP/2 flow control window size.http2MaxFrameSize
(int http2MaxFrameSize) Sets the maximum size of HTTP/2 frame that can be received.http2MaxHeaderListSize
(long http2MaxHeaderListSize) Sets the maximum size of headers that can be received.http2MaxResetFramesPerWindow
(int http2MaxResetFramesPerWindow, int http2MaxResetFramesWindowSeconds) Sets the maximum number of RST frames that are allowed per window before the connection is closed.http2MaxStreamsPerConnection
(long http2MaxStreamsPerConnection) Sets the maximum number of concurrent streams per HTTP/2 connection.https
(int port) Adds an HTTPS port that listens on all available network interfaces.https
(InetSocketAddress localAddress) Adds an HTTPS port that listens to the specifiedlocalAddress
.idleTimeout
(Duration idleTimeout) Sets the idle timeout of a connection for keep-alive.idleTimeout
(Duration idleTimeout, boolean keepAliveOnPing) Sets the idle timeout of a connection for keep-alive and whether to prevent connection connection going idle when an HTTP/2 PING frame or"OPTIONS * HTTP/1.1"
request is received.idleTimeoutMillis
(long idleTimeoutMillis) Sets the idle timeout of a connection in milliseconds for keep-alive.idleTimeoutMillis
(long idleTimeoutMillis, boolean keepAliveOnPing) Sets the idle timeout of a connection in milliseconds for keep-alive and whether to prevent connection going idle when an HTTP/2 PING frame or"OPTIONS * HTTP/1.1"
request is received.localPort
(int port, SessionProtocol... protocols) Adds a newServerPort
that listens to the loopbacklocalAddress
using the specifiedSessionProtocol
s.localPort
(int port, Iterable<SessionProtocol> protocols) Adds a newServerPort
that listens to the loopbacklocalAddress
using the specifiedSessionProtocol
s.maxConnectionAge
(Duration maxConnectionAge) Sets the maximum allowed age of a connection for keep-alive.maxConnectionAgeMillis
(long maxConnectionAgeMillis) Sets the maximum allowed age of a connection in millis for keep-alive.maxNumConnections
(int maxNumConnections) Sets the maximum allowed number of open connections.maxNumRequestsPerConnection
(int maxNumRequestsPerConnection) Sets the maximum allowed number of requests that can be served through one connection.maxRequestLength
(long maxRequestLength) Sets the maximum allowed length of the content decoded at the session layer.meterRegistry
(MeterRegistry meterRegistry) Sets theMeterRegistry
that collects various stats.multipartUploadsLocation
(Path path) Sets thePath
for storing upload file through multipart/form-data.pingInterval
(Duration pingInterval) Sets the HTTP/2 PING interval.pingIntervalMillis
(long pingIntervalMillis) Sets the HTTP/2 PING interval.port
(int port, SessionProtocol... protocols) Adds a newServerPort
that listens to the specifiedport
of all available network interfaces using the specifiedSessionProtocol
s.port
(int port, Iterable<SessionProtocol> protocols) Adds a newServerPort
that listens to the specifiedport
of all available network interfaces using the specifiedSessionProtocol
s.port
(ServerPort port) Adds the specifiedServerPort
.port
(InetSocketAddress localAddress, SessionProtocol... protocols) Adds a newServerPort
that listens to the specifiedlocalAddress
using the specifiedSessionProtocol
s.port
(InetSocketAddress localAddress, Iterable<SessionProtocol> protocols) Adds a newServerPort
that listens to the specifiedlocalAddress
using the specifiedSessionProtocol
s.proxyProtocolMaxTlvSize
(int proxyProtocolMaxTlvSize) Sets the maximum size of additional data for PROXY protocol.rejectedRouteHandler
(RejectedRouteHandler handler) Sets theRejectedRouteHandler
which will be invoked when an attempt to bind anHttpService
at a certainRoute
is rejected.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
(Function<? super RoutingContext, ? extends RequestId> requestIdGenerator) requestIdGenerator
(Supplier<? extends RequestId> requestIdSupplier) Deprecated.requestTimeout
(Duration requestTimeout) Sets the timeout of a request.requestTimeoutMillis
(long requestTimeoutMillis) Sets the timeout of a request in milliseconds.route()
Returns aServiceBindingBuilder
which is for binding anHttpService
fluently.Returns aDecoratingServiceBindingBuilder
which is for binding adecorator
fluently.serverListener
(ServerListener serverListener) Adds the specifiedServerListener
.service
(HttpServiceWithRoutes serviceWithRoutes, Iterable<? extends Function<? super HttpService, ? extends HttpService>> decorators) Decorates and binds the specifiedHttpServiceWithRoutes
at multipleRoute
s of the defaultVirtualHost
.final ServerBuilder
service
(HttpServiceWithRoutes serviceWithRoutes, Function<? super HttpService, ? extends HttpService>... decorators) Decorates and binds the specifiedHttpServiceWithRoutes
at multipleRoute
s of the defaultVirtualHost
.service
(Route route, HttpService service) service
(String pathPattern, HttpService service) Binds the specifiedHttpService
at the specified path pattern of the defaultVirtualHost
.serviceUnder
(String pathPrefix, HttpService service) Binds the specifiedHttpService
under the specified directory of the defaultVirtualHost
.serviceWorkerGroup
(int numThreads) Uses a newly createdEventLoopGroup
with the specified number of threads for runningService.serve(ServiceRequestContext, Request)
.serviceWorkerGroup
(EventLoopGroup serviceWorkerGroup, boolean shutdownOnStop) Sets the workerEventLoopGroup
which is responsible for runningService.serve(ServiceRequestContext, Request)
.setHeader
(CharSequence name, Object value) Adds the default HTTP header for anHttpResponse
served by the defaultVirtualHost
.setHeaders
(Iterable<? extends Map.Entry<? extends CharSequence, ?>> defaultHeaders) Sets the default HTTP headers for anHttpResponse
served by the defaultVirtualHost
.startStopExecutor
(Executor startStopExecutor) Sets theExecutor
which will invoke the callbacks ofServer.start()
,Server.stop()
andServerListener
.successFunction
(SuccessFunction successFunction) Sets aSuccessFunction
that determines whether a request was handled successfully or not.Configures SSL or TLS with the specifiedkeyCertChainFile
and cleartextkeyFile
.Configures SSL or TLS with the specifiedkeyCertChainFile
,keyFile
andkeyPassword
.tls
(InputStream keyCertChainInputStream, InputStream keyInputStream) Configures SSL or TLS with the specifiedkeyCertChainInputStream
and cleartextkeyInputStream
.tls
(InputStream keyCertChainInputStream, InputStream keyInputStream, @Nullable String keyPassword) Configures SSL or TLS of this with the specifiedkeyCertChainInputStream
,keyInputStream
andkeyPassword
.tls
(PrivateKey key, @Nullable String keyPassword, Iterable<? extends X509Certificate> keyCertChain) tls
(PrivateKey key, @Nullable String keyPassword, X509Certificate... keyCertChain) tls
(PrivateKey key, Iterable<? extends X509Certificate> keyCertChain) Configures SSL or TLS with the specified cleartextPrivateKey
andX509Certificate
chain.tls
(PrivateKey key, X509Certificate... keyCertChain) Configures SSL or TLS with the specified cleartextPrivateKey
andX509Certificate
chain.tls
(KeyManagerFactory keyManagerFactory) Configures SSL or TLS with the specifiedKeyManagerFactory
.Deprecated.It's not recommended to enable this option.tlsAllowUnsafeCiphers
(boolean tlsAllowUnsafeCiphers) Deprecated.It's not recommended to enable this option.tlsCustomizer
(Consumer<? super SslContextBuilder> tlsCustomizer) Adds theConsumer
which can arbitrarily configure theSslContextBuilder
that will be applied to the SSL session.Configures SSL or TLS of theServer
with an auto-generated self-signed certificate.tlsSelfSigned
(boolean tlsSelfSigned) Configures SSL or TLS of theServer
with an auto-generated self-signed certificate.unhandledExceptionsReportInterval
(Duration unhandledExceptionsReportInterval) Sets the interval between reporting exceptions which is not handled or logged by any decorators or services such asLoggingService
.unhandledExceptionsReportIntervalMillis
(long unhandledExceptionsReportIntervalMillis) Sets the interval between reporting exceptions which is not handled or logged by any decorators or services such asLoggingService
.verboseResponses
(boolean verboseResponses) Sets whether the verbose response mode is enabled.virtualHost
(int port) Adds the port-based virtual host with the specifiedport
.virtualHost
(String hostnamePattern) Adds the name-based virtual host.virtualHost
(String defaultHostname, String hostnamePattern) Adds the name-based virtual host.withDefaultVirtualHost
(Consumer<? super VirtualHostBuilder> customizer) Configures the defaultVirtualHost
with thecustomizer
.withRoute
(Consumer<? super ServiceBindingBuilder> customizer) withVirtualHost
(Consumer<? super VirtualHostBuilder> customizer) Configures aVirtualHost
with thecustomizer
.workerGroup
(int numThreads) Uses a newly createdEventLoopGroup
with the specified number of threads for performing socket I/O and runningService.serve(ServiceRequestContext, Request)
.workerGroup
(EventLoopGroup workerGroup, boolean shutdownOnStop) Sets the workerEventLoopGroup
which is responsible for performing socket I/O and runningService.serve(ServiceRequestContext, Request)
.
-
Method Details
-
http
Adds an HTTP port that listens on all available network interfaces.- Parameters:
port
- the HTTP port number.- See Also:
-
http
Adds an HTTP port that listens to the specifiedlocalAddress
.- Parameters:
localAddress
- the local address to bind- See Also:
-
https
Adds an HTTPS port that listens on all available network interfaces.- Parameters:
port
- the HTTPS port number.- See Also:
-
https
Adds an HTTPS port that listens to the specifiedlocalAddress
.- Parameters:
localAddress
- the local address to bind- See Also:
-
port
Adds a newServerPort
that listens to the specifiedport
of all available network interfaces using the specifiedSessionProtocol
s. Specify multiple protocols to serve more than one protocol on the same port:ServerBuilder sb = Server.builder(); // Serve both HTTP and HTTPS at port 8080. sb.port(8080, SessionProtocol.HTTP, SessionProtocol.HTTPS); // Enable HTTPS with PROXY protocol support at port 8443. sb.port(8443, SessionProtocol.PROXY, SessionProtocol.HTTPS);
-
port
Adds a newServerPort
that listens to the specifiedport
of all available network interfaces using the specifiedSessionProtocol
s. Specify multiple protocols to serve more than one protocol on the same port:ServerBuilder sb = Server.builder(); // Serve both HTTP and HTTPS at port 8080. sb.port(8080, Arrays.asList(SessionProtocol.HTTP, SessionProtocol.HTTPS)); // Enable HTTPS with PROXY protocol support at port 8443. sb.port(8443, Arrays.asList(SessionProtocol.PROXY, SessionProtocol.HTTPS));
-
port
Adds a newServerPort
that listens to the specifiedlocalAddress
using the specifiedSessionProtocol
s. Specify multiple protocols to serve more than one protocol on the same port:ServerBuilder sb = Server.builder(); // Serve both HTTP and HTTPS at port 8080. sb.port(new InetSocketAddress(8080), SessionProtocol.HTTP, SessionProtocol.HTTPS); // Enable HTTPS with PROXY protocol support at port 8443. sb.port(new InetSocketAddress(8443), SessionProtocol.PROXY, SessionProtocol.HTTPS);
-
port
Adds a newServerPort
that listens to the specifiedlocalAddress
using the specifiedSessionProtocol
s. Specify multiple protocols to serve more than one protocol on the same port:ServerBuilder sb = Server.builder(); // Serve both HTTP and HTTPS at port 8080. sb.port(new InetSocketAddress(8080), Arrays.asList(SessionProtocol.HTTP, SessionProtocol.HTTPS)); // Enable HTTPS with PROXY protocol support at port 8443. sb.port(new InetSocketAddress(8443), Arrays.asList(SessionProtocol.PROXY, SessionProtocol.HTTPS));
-
port
Adds the specifiedServerPort
. -
localPort
Adds a newServerPort
that listens to the loopbacklocalAddress
using the specifiedSessionProtocol
s. Specify multiple protocols to serve more than one protocol on the same port:ServerBuilder sb = Server.builder(); sb.localPort(8080, SessionProtocol.HTTP, SessionProtocol.HTTPS);
-
localPort
Adds a newServerPort
that listens to the loopbacklocalAddress
using the specifiedSessionProtocol
s. Specify multiple protocols to serve more than one protocol on the same port:ServerBuilder sb = Server.builder(); sb.localPort(8080, Arrays.asList(SessionProtocol.HTTP, SessionProtocol.HTTPS));
-
channelOption
Sets theChannelOption
of the server socket bound byServer
. Note that the previously added option will be overridden if the same option is set again.ServerBuilder sb = Server.builder(); sb.channelOption(ChannelOption.BACKLOG, 1024);
-
childChannelOption
Sets theChannelOption
of sockets accepted byServer
. Note that the previously added option will be overridden if the same option is set again.ServerBuilder sb = Server.builder(); sb.childChannelOption(ChannelOption.SO_REUSEADDR, true) .childChannelOption(ChannelOption.SO_KEEPALIVE, true);
-
childChannelPipelineCustomizer
@UnstableApi public ServerBuilder childChannelPipelineCustomizer(Consumer<? super ChannelPipeline> childChannelPipelineCustomizer) (Advanced users only) Adds theConsumer
that customizes the NettyChannelPipeline
. This customizer is run right after the initial set ofChannelHandler
s are configured. This customizer is no-op by default.Note that usage of this customizer is an advanced feature and may produce unintended side effects, including complete breakdown. It is not recommended if you are not familiar with Armeria and Netty internals.
-
workerGroup
Sets the workerEventLoopGroup
which is responsible for performing socket I/O and runningService.serve(ServiceRequestContext, Request)
. If not set, the common worker group is used.- Parameters:
shutdownOnStop
- whether to shut down the workerEventLoopGroup
when theServer
stops
-
workerGroup
Uses a newly createdEventLoopGroup
with the specified number of threads for performing socket I/O and runningService.serve(ServiceRequestContext, Request)
. The workerEventLoopGroup
will be shut down when theServer
stops.- Parameters:
numThreads
- the number of event loop threads
-
serviceWorkerGroup
@UnstableApi public ServerBuilder serviceWorkerGroup(EventLoopGroup serviceWorkerGroup, boolean shutdownOnStop) Sets the workerEventLoopGroup
which is responsible for runningService.serve(ServiceRequestContext, Request)
. If not set, the value set via workerGroup(EventLoopGroup, boolean) or workerGroup(int) is used.- Parameters:
shutdownOnStop
- whether to shut down the workerEventLoopGroup
when theServer
stops
-
serviceWorkerGroup
Uses a newly createdEventLoopGroup
with the specified number of threads for runningService.serve(ServiceRequestContext, Request)
. The workerEventLoopGroup
will be shut down when theServer
stops.- Parameters:
numThreads
- the number of event loop threads
-
startStopExecutor
Sets theExecutor
which will invoke the callbacks ofServer.start()
,Server.stop()
andServerListener
. -
maxNumConnections
Sets the maximum allowed number of open connections. -
idleTimeoutMillis
Sets the idle timeout of a connection in milliseconds for keep-alive.- Parameters:
idleTimeoutMillis
- the timeout in milliseconds.0
disables the timeout.
-
idleTimeoutMillis
@UnstableApi public ServerBuilder idleTimeoutMillis(long idleTimeoutMillis, boolean keepAliveOnPing) Sets the idle timeout of a connection in milliseconds for keep-alive and whether to prevent connection going idle when an HTTP/2 PING frame or"OPTIONS * HTTP/1.1"
request is received.- Parameters:
idleTimeoutMillis
- the timeout in milliseconds.0
disables the timeout.keepAliveOnPing
- whether to reset idle timeout on HTTP/2 PING frame, OPTIONS * request or not.
-
idleTimeout
Sets the idle timeout of a connection for keep-alive.- Parameters:
idleTimeout
- the timeout.0
disables the timeout.
-
idleTimeout
Sets the idle timeout of a connection for keep-alive and whether to prevent connection connection going idle when an HTTP/2 PING frame or"OPTIONS * HTTP/1.1"
request is received.- Parameters:
idleTimeout
- the timeout.0
disables the timeout.keepAliveOnPing
- whether to reset idle timeout on HTTP/2 PING frame, OPTIONS * request or not.
-
pingIntervalMillis
Sets the HTTP/2 PING interval.Note that this settings is only in effect when
idleTimeoutMillis(long)
} oridleTimeout(Duration)
is greater than the specified PING interval.The minimum allowed PING interval is 1000L milliseconds.
0
means the server will not send PING frames on an HTTP/2 connection.- Throws:
IllegalArgumentException
- if the specifiedpingIntervalMillis
is smaller than 1000L milliseconds.
-
pingInterval
Sets the HTTP/2 PING interval.Note that this settings is only in effect when
idleTimeoutMillis(long)
} oridleTimeout(Duration)
is greater than the specified PING interval.The minimum allowed PING interval is 1000L milliseconds.
0
means the server will not send PING frames on an HTTP/2 connection.- Throws:
IllegalArgumentException
- if the specifiedpingInterval
is smaller than 1000L milliseconds.
-
maxConnectionAgeMillis
Sets the maximum allowed age of a connection in millis for keep-alive. A connection is disconnected after the specifiedmaxConnectionAgeMillis
since the connection was established. This option is disabled by default, which means unlimited.- Parameters:
maxConnectionAgeMillis
- the maximum connection age in millis.0
disables the limit.- Throws:
IllegalArgumentException
- if the specifiedmaxConnectionAgeMillis
is smaller than 1000L milliseconds.
-
maxConnectionAge
Sets the maximum allowed age of a connection for keep-alive. A connection is disconnected after the specifiedmaxConnectionAge
since the connection was established. This option is disabled by default, which means unlimited.- Parameters:
maxConnectionAge
- the maximum connection age.0
disables the limit.- Throws:
IllegalArgumentException
- if the specifiedmaxConnectionAge
is smaller than 1000L milliseconds.
-
connectionDrainDurationMicros
Sets the connection drain duration in micros for the connection shutdown. At the beginning of the connection drain server signals the clients that the connection shutdown is imminent but still accepts in flight requests. After the connection drain end server stops accepting new requests. Also, seeconnectionDrainDuration(Duration)
.Note that HTTP/1 doesn't support draining as described here, so for HTTP/1 drain duration is always
0
, which means the connection will be closed immediately as soon as the current in-progress request is handled.- Parameters:
durationMicros
- the drain duration.0
disables the drain.
-
connectionDrainDuration
Sets the connection drain duration in micros for the connection shutdown. At the beginning of the connection drain server signals the clients that the connection shutdown is imminent but still accepts in flight requests. After the connection drain end server stops accepting new requests. Also, seeconnectionDrainDurationMicros(long)
.Note that HTTP/1 doesn't support draining as described here, so for HTTP/1 drain duration is always
0
.- Parameters:
duration
- the drain period.Duration.ZERO
or negative value disables the drain period.
-
maxNumRequestsPerConnection
Sets the maximum allowed number of requests that can be served through one connection. This option is disabled by default, which means unlimited.- Parameters:
maxNumRequestsPerConnection
- the maximum number of requests per connection.0
disables the limit.
-
http2InitialConnectionWindowSize
Sets the initial connection-level HTTP/2 flow control window size. Larger values can lower stream warmup time at the expense of being easier to overload the server. Defaults toFlags.defaultHttp2InitialConnectionWindowSize()
. Note that this setting affects the connection-level window size, not the window size of streams.- See Also:
-
http2InitialStreamWindowSize
Sets the initial stream-level HTTP/2 flow control window size. Larger values can lower stream warmup time at the expense of being easier to overload the server. Defaults toFlags.defaultHttp2InitialStreamWindowSize()
. Note that this setting affects the stream-level window size, not the window size of connections.- See Also:
-
http2MaxStreamsPerConnection
Sets the maximum number of concurrent streams per HTTP/2 connection. Unset means there is no limit on the number of concurrent streams. Note, this differs frommaxNumConnections()
, which is the maximum number of HTTP/2 connections themselves, not the streams that are multiplexed over each. -
http2MaxResetFramesPerWindow
@UnstableApi public ServerBuilder http2MaxResetFramesPerWindow(int http2MaxResetFramesPerWindow, int http2MaxResetFramesWindowSeconds) Sets the maximum number of RST frames that are allowed per window before the connection is closed. This allows to protect against the remote peer flooding us with such frames and using up a lot of CPU. Defaults toFlags.defaultServerHttp2MaxResetFramesPerMinute()
.Note that
0
for any of the parameters means no protection should be applied. -
http2MaxFrameSize
Sets the maximum size of HTTP/2 frame that can be received. Defaults toFlags.defaultHttp2MaxFrameSize()
. -
http2MaxHeaderListSize
Sets the maximum size of headers that can be received. Defaults toFlags.defaultHttp2MaxHeaderListSize()
. -
http1MaxInitialLineLength
Sets the maximum length of an HTTP/1 response initial line. -
http1MaxHeaderSize
Sets the maximum length of all headers in an HTTP/1 response. -
http1MaxChunkSize
Sets the maximum length of each chunk in an HTTP/1 response content. The content or a chunk longer than this value will be split into smaller chunks so that their lengths never exceed it. -
gracefulShutdownTimeoutMillis
Sets the amount of time to wait after callingServer.stop()
for requests to go away before actually shutting down.- Parameters:
quietPeriodMillis
- the number of milliseconds to wait for active requests to go end before shutting down. 0 means the server will stop right away without waiting.timeoutMillis
- the number of milliseconds to wait before shutting down the server regardless of active requests. This should be set to a time greater thanquietPeriodMillis
to ensure the server shuts down even if there is a stuck request.
-
gracefulShutdownTimeout
Sets the amount of time to wait after callingServer.stop()
for requests to go away before actually shutting down.- Parameters:
quietPeriod
- the number of milliseconds to wait for active requests to go end before shutting down.Duration.ZERO
means the server will stop right away without waiting.timeout
- the amount of time to wait before shutting down the server regardless of active requests. This should be set to a time greater thanquietPeriod
to ensure the server shuts down even if there is a stuck request.
-
requestAutoAbortDelay
Sets the amount of time to wait before aborting anHttpRequest
when its correspondingHttpResponse
is complete. This may be useful when you want to receive additional data even after closing the response. SpecifyDuration.ZERO
to abort theHttpRequest
immediately. Any negative value will not abort the request automatically. There is no delay by default. -
requestAutoAbortDelayMillis
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 receive additional data even after closing the response. Specify0
to abort theHttpRequest
immediately. Any negative value will not abort the request automatically. There is no delay by default. -
multipartUploadsLocation
Sets thePath
for storing upload file through multipart/form-data.- Parameters:
path
- the path of the directory stores the file.
-
blockingTaskExecutor
public ServerBuilder blockingTaskExecutor(ScheduledExecutorService blockingTaskExecutor, boolean shutdownOnStop) Sets theScheduledExecutorService
dedicated to the execution of blocking tasks or invocations. If not set, the common pool is used.- Parameters:
shutdownOnStop
- whether to shut down theScheduledExecutorService
when theServer
stops
-
blockingTaskExecutor
public ServerBuilder blockingTaskExecutor(BlockingTaskExecutor blockingTaskExecutor, boolean shutdownOnStop) Sets theBlockingTaskExecutor
dedicated to the execution of blocking tasks or invocations. If not set, the common pool is used.- Parameters:
shutdownOnStop
- whether to shut down theBlockingTaskExecutor
when theServer
stops
-
blockingTaskExecutor
Uses a newly createdBlockingTaskExecutor
with the specified number of threads dedicated to the execution of blocking tasks or invocations. TheBlockingTaskExecutor
will be shut down when theServer
stops.- Parameters:
numThreads
- the number of threads in the executor
-
successFunction
Sets aSuccessFunction
that determines whether a request was handled successfully or not. If unspecified,SuccessFunction.ofDefault()
is used. -
meterRegistry
Sets theMeterRegistry
that collects various stats. -
defaultServiceNaming
Sets a global naming rule for the name of services. This property can be overridden viaVirtualHostBuilder.defaultServiceNaming(ServiceNaming)
. The overriding is also possible if service-level naming rule is set viaServiceBindingBuilder.defaultServiceNaming(ServiceNaming)
.- See Also:
-
accessLogFormat
Sets the format of thisServer
's access log. The specifiedaccessLogFormat
would be parsed byAccessLogWriter.custom(String)
. -
accessLogWriter
Sets an access log writer of thisServer
.AccessLogWriter.disabled()
is used by default.- Parameters:
shutdownOnStop
- whether to shut down theAccessLogWriter
when theServer
stops
-
proxyProtocolMaxTlvSize
Sets the maximum size of additional data for PROXY protocol. The default value of this property is 65319.Note: limiting TLV size only affects processing of v2, binary headers. Also, as allowed by the 1.5 spec, TLV data is currently ignored. For maximum performance, it would be best to configure your upstream proxy host to NOT send TLV data and set this property to
0
. -
tls
Description copied from interface:TlsSetters
Configures SSL or TLS with the specifiedkeyCertChainFile
and cleartextkeyFile
.- Specified by:
tls
in interfaceTlsSetters
-
tls
public ServerBuilder tls(File keyCertChainFile, File keyFile, @Nullable @Nullable String keyPassword) Description copied from interface:TlsSetters
Configures SSL or TLS with the specifiedkeyCertChainFile
,keyFile
andkeyPassword
.- Specified by:
tls
in interfaceTlsSetters
-
tls
Description copied from interface:TlsSetters
Configures SSL or TLS with the specifiedkeyCertChainInputStream
and cleartextkeyInputStream
.- Specified by:
tls
in interfaceTlsSetters
-
tls
public ServerBuilder tls(InputStream keyCertChainInputStream, InputStream keyInputStream, @Nullable @Nullable String keyPassword) Description copied from interface:TlsSetters
Configures SSL or TLS of this with the specifiedkeyCertChainInputStream
,keyInputStream
andkeyPassword
.- Specified by:
tls
in interfaceTlsSetters
-
tls
Description copied from interface:TlsSetters
Configures SSL or TLS with the specified cleartextPrivateKey
andX509Certificate
chain.- Specified by:
tls
in interfaceTlsSetters
-
tls
Description copied from interface:TlsSetters
Configures SSL or TLS with the specified cleartextPrivateKey
andX509Certificate
chain.- Specified by:
tls
in interfaceTlsSetters
-
tls
public ServerBuilder tls(PrivateKey key, @Nullable @Nullable String keyPassword, X509Certificate... keyCertChain) Description copied from interface:TlsSetters
- Specified by:
tls
in interfaceTlsSetters
-
tls
public ServerBuilder tls(PrivateKey key, @Nullable @Nullable String keyPassword, Iterable<? extends X509Certificate> keyCertChain) Description copied from interface:TlsSetters
- Specified by:
tls
in interfaceTlsSetters
-
tls
Description copied from interface:TlsSetters
Configures SSL or TLS with the specifiedKeyManagerFactory
.- Specified by:
tls
in interfaceTlsSetters
-
tlsSelfSigned
Configures SSL or TLS of theServer
with an auto-generated self-signed certificate. Note: You should never use this in production but only for a testing purpose.- See Also:
-
tlsSelfSigned
Configures SSL or TLS of theServer
with an auto-generated self-signed certificate. Note: You should never use this in production but only for a testing purpose.- See Also:
-
tlsCustomizer
Description copied from interface:TlsSetters
Adds theConsumer
which can arbitrarily configure theSslContextBuilder
that will be applied to the SSL session.- Specified by:
tlsCustomizer
in interfaceTlsSetters
-
tlsAllowUnsafeCiphers
Deprecated.It's not recommended to enable this option. Use it only when you have no other way to communicate with an insecure peer than this.Allows the bad cipher suites listed in RFC7540 for TLS handshake.Note that enabling this option increases the security risk of your connection. Use it only when you must communicate with a legacy system that does not support secure cipher suites. See Section 9.2.2, RFC7540 for more information. This option is disabled by default.
-
tlsAllowUnsafeCiphers
Deprecated.It's not recommended to enable this option. Use it only when you have no other way to communicate with an insecure peer than this.Allows the bad cipher suites listed in RFC7540 for TLS handshake.Note that enabling this option increases the security risk of your connection. Use it only when you must communicate with a legacy system that does not support secure cipher suites. See Section 9.2.2, RFC7540 for more information. This option is disabled by default.
- Parameters:
tlsAllowUnsafeCiphers
- Whether to allow the unsafe ciphers
-
contextPath
Returns aContextPathServicesBuilder
which bindsHttpService
s under the specified context paths.- See Also:
-
contextPath
Returns aContextPathServicesBuilder
which bindsHttpService
s under the specified context paths.- See Also:
-
withRoute
-
route
Returns aServiceBindingBuilder
which is for binding anHttpService
fluently. -
routeDecorator
Returns aDecoratingServiceBindingBuilder
which is for binding adecorator
fluently. The specified decorator(s) is/are executed in reverse order of the insertion. -
serviceUnder
Binds the specifiedHttpService
under the specified directory of the defaultVirtualHost
. If the specifiedHttpService
is anHttpServiceWithRoutes
, thepathPrefix
is added to eachRoute
ofServiceWithRoutes.routes()
. For example, theserviceWithRoutes
in the following code will be bound to ("/foo/bar"
) and ("/foo/baz"
):> HttpServiceWithRoutes serviceWithRoutes = new HttpServiceWithRoutes() { > @Override > public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) { ... } > > @Override > public Set<Route> routes() { > return Set.of(Route.builder().path("/bar").build(), > Route.builder().path("/baz").build()); > } > }; > > Server.builder() > .serviceUnder("/foo", serviceWithRoutes) > .build();
-
service
Binds the specifiedHttpService
at the specified path pattern of the defaultVirtualHost
. e.g./login
(no path parameters)/users/{userId}
(curly-brace style)/list/:productType/by/:ordering
(colon style)exact:/foo/bar
(exact match)prefix:/files
(prefix match)glob:/~*/downloads/**
(glob pattern)regex:^/files/(?<filePath>.*)$
(regular expression)
- Throws:
IllegalArgumentException
- if the specified path pattern is invalid
-
service
-
service
public ServerBuilder service(HttpServiceWithRoutes serviceWithRoutes, Iterable<? extends Function<? super HttpService, ? extends HttpService>> decorators) Decorates and binds the specifiedHttpServiceWithRoutes
at multipleRoute
s of the defaultVirtualHost
.- Parameters:
serviceWithRoutes
- theHttpServiceWithRoutes
.decorators
- the decorator functions, which will be applied in the order specified.
-
service
@SafeVarargs public final ServerBuilder service(HttpServiceWithRoutes serviceWithRoutes, Function<? super HttpService, ? extends HttpService>... decorators) Decorates and binds the specifiedHttpServiceWithRoutes
at multipleRoute
s of the defaultVirtualHost
.- Parameters:
serviceWithRoutes
- theHttpServiceWithRoutes
.decorators
- the decorator functions, which will be applied in the order specified.
-
annotatedService
Binds the specified annotated service object under the path prefix"/"
. -
annotatedService
Binds the specified annotated service object under the path prefix"/"
.- Parameters:
exceptionHandlersAndConverters
- theExceptionHandlerFunction
s, theRequestConverterFunction
s and/or theResponseConverterFunction
s
-
annotatedService
public ServerBuilder annotatedService(Object service, Function<? super HttpService, ? extends HttpService> decorator, Object... exceptionHandlersAndConverters) Binds the specified annotated service object under the path prefix"/"
.- Parameters:
exceptionHandlersAndConverters
- theExceptionHandlerFunction
s, theRequestConverterFunction
s and/or theResponseConverterFunction
s
-
annotatedService
Binds the specified annotated service object under the specified path prefix. -
annotatedService
public ServerBuilder annotatedService(String pathPrefix, Object service, Object... exceptionHandlersAndConverters) Binds the specified annotated service object under the specified path prefix.- Parameters:
exceptionHandlersAndConverters
- theExceptionHandlerFunction
s, theRequestConverterFunction
s and/or theResponseConverterFunction
s
-
annotatedService
public ServerBuilder annotatedService(String pathPrefix, Object service, Function<? super HttpService, ? extends HttpService> decorator, Object... exceptionHandlersAndConverters) Binds the specified annotated service object under the specified path prefix.- Parameters:
exceptionHandlersAndConverters
- theExceptionHandlerFunction
s, theRequestConverterFunction
s and/or theResponseConverterFunction
s
-
annotatedService
public ServerBuilder annotatedService(String pathPrefix, Object service, Iterable<?> exceptionHandlersAndConverters) Binds the specified annotated service object under the specified path prefix.- Parameters:
exceptionHandlersAndConverters
- theExceptionHandlerFunction
s, theRequestConverterFunction
s and/or theResponseConverterFunction
s
-
annotatedService
public ServerBuilder annotatedService(String pathPrefix, Object service, Function<? super HttpService, ? extends HttpService> decorator, Iterable<?> exceptionHandlersAndConverters) Binds the specified annotated service object under the specified path prefix.- Parameters:
exceptionHandlersAndConverters
- theExceptionHandlerFunction
, theRequestConverterFunction
and/or theResponseConverterFunction
-
annotatedService
public ServerBuilder annotatedService(String pathPrefix, Object service, Function<? super HttpService, ? extends HttpService> decorator, Iterable<? extends ExceptionHandlerFunction> exceptionHandlerFunctions, Iterable<? extends RequestConverterFunction> requestConverterFunctions, Iterable<? extends ResponseConverterFunction> responseConverterFunctions) Binds the specified annotated service object under the specified path prefix.- Parameters:
exceptionHandlerFunctions
- theExceptionHandlerFunction
srequestConverterFunctions
- theRequestConverterFunction
sresponseConverterFunctions
- theResponseConverterFunction
s
-
annotatedService
Returns anAnnotatedServiceBindingBuilder
to build annotated service. -
serverListener
Adds the specifiedServerListener
. -
defaultHostname
Sets the default hostname of the defaultVirtualHostBuilder
. -
baseContextPath
Sets the base context path for thisServerBuilder
. Services and decorators added to thisServerBuilder
will be prefixed by the specifiedbaseContextPath
. If a service is bound to a scopedcontextPath(String...)
, thebaseContextPath
will be prepended to thecontextPath
.Server .builder() .baseContextPath("/api") // The following service will be served at '/api/v1/items'. .service("/v1/items", itemService) .contextPath("/v2") // The following service will be served at '/api/v2/users'. .service("/users", usersService) .and() // end of the "/v2" contextPath .build();
Note that the
baseContextPath
won't be applied toVirtualHost
s added to thisServer
. To configure the context path for individualVirtualHost
s, useVirtualHostBuilder.baseContextPath(String)
instead. -
withDefaultVirtualHost
Configures the defaultVirtualHost
with thecustomizer
. -
defaultVirtualHost
Returns theVirtualHostBuilder
for building the default name-based virtual host. -
withVirtualHost
Configures aVirtualHost
with thecustomizer
. -
virtualHost
Adds the name-based virtual host.- Parameters:
hostnamePattern
- virtual host name regular expression- Returns:
VirtualHostBuilder
for building the virtual host
-
virtualHost
Adds the name-based virtual host.- Parameters:
defaultHostname
- default hostname of this virtual hosthostnamePattern
- virtual host name regular expression- Returns:
VirtualHostBuilder
for building the virtual host
-
virtualHost
Adds the port-based virtual host with the specifiedport
. The returned virtual host will have a catch-all (wildcard host) name pattern that allows all host names.Note that you cannot configure TLS to the port-based virtual host. Configure it to the
ServerBuilder
or a name-based virtual host.- Parameters:
port
- the port number that this virtual host binds to- Returns:
VirtualHostBuilder
for building the virtual host
-
decorator
Decorates allHttpService
s with the specifieddecorator
. The specified decorator(s) is/are executed in reverse order of the insertion.- Parameters:
decorator
- theFunction
that decoratesHttpService
s
-
decorator
Decorates allHttpService
s with the specifiedDecoratingHttpServiceFunction
. The specified decorator(s) is/are executed in reverse order of the insertion.- Parameters:
decoratingHttpServiceFunction
- theDecoratingHttpServiceFunction
that decoratesHttpService
s
-
decorator
public ServerBuilder decorator(String pathPattern, Function<? super HttpService, ? extends HttpService> decorator) DecoratesHttpService
s whoseRoute
matches the specifiedpathPattern
. The specified decorator(s) is/are executed in reverse order of the insertion. -
decorator
public ServerBuilder decorator(String pathPattern, DecoratingHttpServiceFunction decoratingHttpServiceFunction) DecoratesHttpService
s whoseRoute
matches the specifiedpathPattern
. The specified decorator(s) is/are executed in reverse order of the insertion.- Parameters:
decoratingHttpServiceFunction
- theDecoratingHttpServiceFunction
that decoratesHttpService
.
-
decorator
public ServerBuilder decorator(Route route, Function<? super HttpService, ? extends HttpService> decorator) DecoratesHttpService
s with the specifiedRoute
. The specified decorator(s) is/are executed in reverse order of the insertion.- Parameters:
route
- the route being decorateddecorator
- theFunction
that decoratesHttpService
which matches the specifiedRoute
-
decorator
public ServerBuilder decorator(Route route, DecoratingHttpServiceFunction decoratingHttpServiceFunction) DecoratesHttpService
s with the specifiedRoute
. The specified decorator(s) is/are executed in reverse order of the insertion.- Parameters:
route
- the route being decorateddecoratingHttpServiceFunction
- theDecoratingHttpServiceFunction
that decoratesHttpService
s
-
decoratorUnder
public ServerBuilder decoratorUnder(String prefix, DecoratingHttpServiceFunction decoratingHttpServiceFunction) DecoratesHttpService
s under the specified directory. The specified decorator(s) is/are executed in reverse order of the insertion.- Parameters:
decoratingHttpServiceFunction
- theDecoratingHttpServiceFunction
that decoratesHttpService
s
-
decoratorUnder
public ServerBuilder decoratorUnder(String prefix, Function<? super HttpService, ? extends HttpService> decorator) DecoratesHttpService
s under the specified directory. The specified decorator(s) is/are executed in reverse order of the insertion. -
errorHandler
Adds theServerErrorHandler
that provides the error responses in case of unexpected exceptions or protocol errors. If multiple handlers are added, the latter is composed with the former usingServerErrorHandler.orElse(ServerErrorHandler)
.Note that the
HttpResponseException
is not handled by theServerErrorHandler
but theHttpResponseException.httpResponse()
is sent as-is. -
clientAddressSources
Sets a list ofClientAddressSource
s which are used to determine where to look for the client address, in the order of preference.Forwarded
header,X-Forwarded-For
header and the source address of a PROXY protocol header will be used by default. -
clientAddressSources
Sets a list ofClientAddressSource
s which are used to determine where to look for the client address, in the order of preference.Forwarded
header,X-Forwarded-For
header and the source address of a PROXY protocol header will be used by default. -
clientAddressTrustedProxyFilter
public ServerBuilder clientAddressTrustedProxyFilter(Predicate<? super InetAddress> clientAddressTrustedProxyFilter) Sets a filter which evaluates whether anInetAddress
of a remote endpoint is trusted. -
clientAddressFilter
Sets a filter which evaluates whether anInetAddress
can be used as a client address. -
clientAddressMapper
public ServerBuilder clientAddressMapper(Function<? super ProxiedAddresses, ? extends InetSocketAddress> clientAddressMapper) Sets aFunction
to use when determining the client address fromProxiedAddresses
. If not set, theProxiedAddresses.sourceAddress()
} is used as a client address. -
accessLogger
Sets the default access logger name for allVirtualHost
s. TheVirtualHost
s which do not have an access logger specified by aVirtualHostBuilder
will have the same accessLogger
named theloggerName
whenbuild()
is called. -
accessLogger
Sets the default accessLogger
for allVirtualHost
s. TheVirtualHost
s which do not have an access logger specified by aVirtualHostBuilder
will have the same accessLogger
whenbuild()
is called. -
accessLogger
Sets the default access logger mapper for allVirtualHost
s. TheVirtualHost
s which do not have an access logger specified by aVirtualHostBuilder
will have an access logger set by themapper
whenbuild()
is called. -
rejectedRouteHandler
Sets theRejectedRouteHandler
which will be invoked when an attempt to bind anHttpService
at a certainRoute
is rejected. By default, the duplicate routes are logged at WARN level. -
disableServerHeader
Sets the response header not to include default"Server"
header. -
disableDateHeader
Sets the response header not to include default"Date"
header. -
addHeader
Adds the default HTTP header for anHttpResponse
served by the defaultVirtualHost
.Note that the default header could be overridden if the same
HttpHeaderNames
are defined in one of the followings: -
addHeaders
@UnstableApi public ServerBuilder addHeaders(Iterable<? extends Map.Entry<? extends CharSequence, ?>> defaultHeaders) Adds the default HTTP headers for anHttpResponse
served by the defaultVirtualHost
.Note that the default headers could be overridden if the same
HttpHeaderNames
are defined in one of the followings: -
setHeader
Adds the default HTTP header for anHttpResponse
served by the defaultVirtualHost
.Note that the default header could be overridden if the same
HttpHeaderNames
are defined in one of the followings: -
setHeaders
@UnstableApi public ServerBuilder setHeaders(Iterable<? extends Map.Entry<? extends CharSequence, ?>> defaultHeaders) Sets the default HTTP headers for anHttpResponse
served by the defaultVirtualHost
.Note that the default headers could be overridden if the same
HttpHeaderNames
are defined in one of the followings: -
requestIdGenerator
@Deprecated public ServerBuilder requestIdGenerator(Supplier<? extends RequestId> requestIdSupplier) Deprecated. -
requestIdGenerator
public ServerBuilder requestIdGenerator(Function<? super RoutingContext, ? extends RequestId> requestIdGenerator) Sets theFunction
that generates aRequestId
for eachRequest
. By default, aRequestId
is generated from a random 64-bit integer.- See Also:
-
requestTimeout
Sets the timeout of a request.- Parameters:
requestTimeout
- the timeout.0
disables the timeout.
-
requestTimeoutMillis
Sets the timeout of a request in milliseconds.- Parameters:
requestTimeoutMillis
- the timeout in milliseconds.0
disables the timeout.
-
maxRequestLength
Sets the maximum allowed length of the content decoded at the session layer. e.g. the content length of an HTTP request.- Parameters:
maxRequestLength
- the maximum allowed length.0
disables the length limit.
-
verboseResponses
Sets whether the verbose response mode is enabled. When enabled, the server responses will contain the exception type and its full stack trace, which may be useful for debugging while potentially insecure. When disabled, the server responses will not expose such server-side details to the client. The default value of this property is retrieved fromFlags.verboseResponses()
. -
annotatedServiceExtensions
public ServerBuilder annotatedServiceExtensions(Iterable<? extends RequestConverterFunction> requestConverterFunctions, Iterable<? extends ResponseConverterFunction> responseConverterFunctions, Iterable<? extends ExceptionHandlerFunction> exceptionHandlerFunctions) Sets theRequestConverterFunction
s,ResponseConverterFunction
andExceptionHandlerFunction
s for creating anAnnotatedServiceExtensions
.- Parameters:
requestConverterFunctions
- theRequestConverterFunction
sresponseConverterFunctions
- theResponseConverterFunction
sexceptionHandlerFunctions
- theExceptionHandlerFunction
s
-
contextHook
Sets theAutoCloseable
which will be called whenever thisRequestContext
is popped from theRequestContextStorage
.- Parameters:
contextHook
- theSupplier
that provides theAutoCloseable
-
dependencyInjector
@UnstableApi public ServerBuilder dependencyInjector(DependencyInjector dependencyInjector, boolean shutdownOnStop) Sets theDependencyInjector
to inject dependencies in annotated services.- Parameters:
dependencyInjector
- theDependencyInjector
to inject dependenciesshutdownOnStop
- whether to shut down theDependencyInjector
when theServer
stops
-
absoluteUriTransformer
@UnstableApi public ServerBuilder absoluteUriTransformer(Function<? super String, String> absoluteUriTransformer) Sets theFunction
that transforms the absolute URI in an HTTP/1 request line into an absolute path. Use this property when you have to handle a client that sends such an HTTP/1 request, because Armeria always assumes that request path is an absolute path and return a400 Bad Request
response otherwise. For example:builder.absoluteUriTransformer(absoluteUri -> { // https://foo.com/bar -> /bar return absoluteUri.replaceFirst("^https://\\.foo\\.com/", "/"); // or.. // return "/proxy?uri=" + URLEncoder.encode(absoluteUri); });
-
http1HeaderNaming
Sets theHttp1HeaderNaming
which converts a lower-cased HTTP/2 header name into another HTTP/1 header name. This is useful when communicating with a legacy system that only supports case-sensitive HTTP/1 headers. -
unhandledExceptionsReportInterval
@UnstableApi public ServerBuilder unhandledExceptionsReportInterval(Duration unhandledExceptionsReportInterval) Sets the interval between reporting exceptions which is not handled or logged by any decorators or services such asLoggingService
.- Parameters:
unhandledExceptionsReportInterval
- the interval between reports, orDuration.ZERO
to disable this feature- Throws:
IllegalArgumentException
- if specifiedinterval
is negative.
-
unhandledExceptionsReportIntervalMillis
@UnstableApi public ServerBuilder unhandledExceptionsReportIntervalMillis(long unhandledExceptionsReportIntervalMillis) Sets the interval between reporting exceptions which is not handled or logged by any decorators or services such asLoggingService
.- Parameters:
unhandledExceptionsReportIntervalMillis
- the interval between reports in milliseconds, or0
to disable this feature- Throws:
IllegalArgumentException
- if specifiedinterval
is negative.
-
build
Returns a newly-createdServer
based on the configuration properties set so far.
-
requestIdGenerator(Function)