public abstract class HttpServer extends Object
bind(TcpServer)
is ultimately called.
Internally, materialization happens in two phases:
tcpConfiguration()
is called to retrieve a ready to use TcpServer
bind(TcpServer)
is calledExamples:
HttpServer.create()
.host("0.0.0.0")
.handle((req, res) -> res.sendString(Flux.just("hello")))
.bind()
.block();
Constructor and Description |
---|
HttpServer() |
Modifier and Type | Method and Description |
---|---|
Mono<? extends DisposableServer> |
bind()
|
protected abstract Mono<? extends DisposableServer> |
bind(TcpServer b)
|
HttpServer |
bindAddress(java.util.function.Supplier<? extends SocketAddress> bindAddressSupplier)
The address to which this server should bind on subscribe.
|
DisposableServer |
bindNow()
Start the server in a blocking fashion, and wait for it to finish initializing
or the startup timeout expires (the startup timeout is
45 seconds). |
DisposableServer |
bindNow(java.time.Duration timeout)
Start the server in a blocking fashion, and wait for it to finish initializing
or the provided startup timeout expires.
|
void |
bindUntilJavaShutdown(java.time.Duration timeout,
java.util.function.Consumer<DisposableServer> onStart)
Start the server in a fully blocking fashion, not only waiting for it to initialize
but also blocking during the full lifecycle of the server.
|
HttpServer |
channelGroup(ChannelGroup channelGroup)
Provide a
ChannelGroup to hold all active connected channels. |
HttpServer |
compress(java.util.function.BiPredicate<HttpServerRequest,HttpServerResponse> predicate)
Enable GZip response compression if the client request presents accept encoding
headers and the provided
Predicate matches. |
HttpServer |
compress(boolean compressionEnabled)
Specifies whether GZip response compression/websocket compression
extension is enabled if the client request
presents accept encoding/websocket extensions headers.
|
HttpServer |
compress(int minResponseSize)
Enable GZip response compression if the client request presents accept encoding
headers AND the response reaches a minimum threshold
|
HttpServer |
cookieCodec(ServerCookieEncoder encoder)
Configure the
ServerCookieEncoder ; ServerCookieDecoder will be
chosen based on the encoder |
HttpServer |
cookieCodec(ServerCookieEncoder encoder,
ServerCookieDecoder decoder)
Configure the
ServerCookieEncoder and ServerCookieDecoder |
static HttpServer |
create()
Prepare an
HttpServer |
HttpServer |
forwarded(java.util.function.BiFunction<ConnectionInfo,HttpRequest,ConnectionInfo> handler)
Specifies a custom request handler for deriving information about the connection.
|
HttpServer |
forwarded(boolean forwardedEnabled)
Specifies whether support for the
"Forwarded" and "X-Forwarded-*"
HTTP request headers for deriving information about the connection is enabled. |
static HttpServer |
from(TcpServer tcpServer)
Prepare an
HttpServer |
HttpServer |
handle(java.util.function.BiFunction<? super HttpServerRequest,? super HttpServerResponse,? extends Publisher<Void>> handler)
Attach an I/O handler to react on a connected client
|
HttpServer |
host(String host)
The host to which this server should bind.
|
HttpServer |
httpRequestDecoder(java.util.function.Function<HttpRequestDecoderSpec,HttpRequestDecoderSpec> requestDecoderOptions)
Configure the
HttpServerCodec 's request decoding options. |
HttpServer |
idleTimeout(java.time.Duration idleTimeout)
Specifies an idle timeout on the connection when it is waiting for an HTTP request (resolution: ms).
|
HttpServer |
metrics(boolean metricsEnabled)
Deprecated.
as of 0.9.7. Use
metrics(boolean, Function) |
HttpServer |
metrics(boolean metricsEnabled,
java.util.function.Function<String,String> uriTagValue)
Whether to enable metrics to be collected and registered in Micrometer's
globalRegistry
under the name Metrics.HTTP_SERVER_PREFIX . |
HttpServer |
metrics(boolean metricsEnabled,
HttpServerMetricsRecorder recorder)
Deprecated.
as of 0.9.7. Use
metrics(boolean, Supplier) |
HttpServer |
metrics(boolean metricsEnabled,
java.util.function.Supplier<? extends HttpServerMetricsRecorder> recorder)
Specifies whether the metrics are enabled on the
HttpServer . |
HttpServer |
metrics(boolean metricsEnabled,
java.util.function.Supplier<? extends HttpServerMetricsRecorder> recorder,
java.util.function.Function<String,String> uriValue)
Specifies whether the metrics are enabled on the
HttpServer . |
HttpServer |
observe(ConnectionObserver observer)
Setup all lifecycle callbacks called on or after
each child
Channel
has been connected and after it has been disconnected. |
HttpServer |
port(int port)
The port to which this server should bind.
|
HttpServer |
protocol(HttpProtocol... supportedProtocols)
The HTTP protocol to support.
|
HttpServer |
proxyProtocol(ProxyProtocolSupportType proxyProtocolSupportType)
Specifies whether support for the
"HAProxy proxy protocol"
for deriving information about the address of the remote peer is enabled. |
HttpServer |
route(java.util.function.Consumer<? super HttpServerRoutes> routesBuilder)
Define routes for the server through the provided
HttpServerRoutes builder. |
HttpServer |
secure(java.util.function.Consumer<? super SslProvider.SslContextSpec> sslProviderBuilder)
Apply an SSL configuration customization via the passed builder.
|
protected TcpServer |
tcpConfiguration()
|
HttpServer |
tcpConfiguration(java.util.function.Function<? super TcpServer,? extends TcpServer> tcpMapper)
Apply
ServerBootstrap configuration given mapper taking currently
configured one and returning a new one to be ultimately used for socket binding. |
HttpServer |
wiretap(boolean enable)
Apply or remove a wire logger configuration using
HttpServer category
and DEBUG logger level |
public static HttpServer create()
HttpServer
HttpServer
public static HttpServer from(TcpServer tcpServer)
HttpServer
HttpServer
public final Mono<? extends DisposableServer> bind()
HttpServer
and return a Mono
of DisposableServer
. If
Mono
is cancelled, the underlying binding will be aborted. Once the DisposableServer
has been emitted and is not necessary anymore, disposing main server
loop must be done by the user via DisposableChannel.dispose()
.
If update configuration phase fails, a Mono.error(Throwable)
will be returnedMono
of DisposableServer
public final DisposableServer bindNow()
45
seconds). The
returned DisposableServer
offers simple server API, including to DisposableChannel.disposeNow()
shut it down in a blocking fashion.DisposableServer
public final DisposableServer bindNow(java.time.Duration timeout)
DisposableServer
offers simple server API, including to DisposableChannel.disposeNow()
shut it down in a blocking fashion.timeout
- max startup timeoutDisposableServer
public final void bindUntilJavaShutdown(java.time.Duration timeout, @Nullable java.util.function.Consumer<DisposableServer> onStart)
sigkill
.
Note: JVM shutdown hook
is added by
this method in order to properly disconnect the server upon receiving a
sigkill
signal.
timeout
- a timeout for server shutdownonStart
- an optional callback on server startpublic final HttpServer compress(boolean compressionEnabled)
Note: Using this method for enabling websocket compression is strongly discouraged.
As of 0.9.5, use WebsocketServerSpec.builder()
for providing websocket configuration.
compressionEnabled
- if true GZip response compression/websocket compression
extension is enabled if the client request presents
accept encoding/websocket extensions headers, otherwise disabled.HttpServer
public final HttpServer compress(int minResponseSize)
minResponseSize
- compression is performed once response size exceeds the given
value in bytesHttpServer
public final HttpServer compress(java.util.function.BiPredicate<HttpServerRequest,HttpServerResponse> predicate)
Predicate
matches.
Note: the passed HttpServerRequest
and HttpServerResponse
should be considered read-only and the implement SHOULD NOT consume or
write the request/response in this predicate.
predicate
- that returns true to compress the response.HttpServer
public final HttpServer forwarded(boolean forwardedEnabled)
"Forwarded"
and "X-Forwarded-*"
HTTP request headers for deriving information about the connection is enabled.forwardedEnabled
- if true support for the "Forwarded"
and "X-Forwarded-*"
HTTP request headers for deriving information about the connection is enabled,
otherwise disabled.HttpServer
public final HttpServer forwarded(java.util.function.BiFunction<ConnectionInfo,HttpRequest,ConnectionInfo> handler)
handler
- the forwarded header handlerHttpServer
public final HttpServer proxyProtocol(ProxyProtocolSupportType proxyProtocolSupportType)
"HAProxy proxy protocol"
for deriving information about the address of the remote peer is enabled.proxyProtocolSupportType
- ProxyProtocolSupportType.ON
to enable support for the "HAProxy proxy protocol"
for deriving information about the address of the remote peer.
ProxyProtocolSupportType.OFF
to disable the proxy protocol support.ProxyProtocolSupportType.AUTO
then each connection of the same HttpServer
will auto detect whether there is proxy protocol,
so HttpServer
can accept requests with or without proxy protocol at the same time.
HttpServer
public final HttpServer bindAddress(java.util.function.Supplier<? extends SocketAddress> bindAddressSupplier)
bindAddressSupplier
- A supplier of the address to bind to.HttpServer
@Deprecated public final HttpServer metrics(boolean metricsEnabled)
metrics(boolean, Function)
globalRegistry
under the name Metrics.HTTP_SERVER_PREFIX
.
Note: It is strongly recommended applications to configure an upper limit for the number of the URI tags. For example:
Metrics.globalRegistry .config() .meterFilter(MeterFilter.maximumAllowableTags(HTTP_SERVER_PREFIX, URI, 100, MeterFilter.deny()));
By default metrics are not enabled.
metricsEnabled
- true enables metrics collection; false disables itHttpServer
public final HttpServer metrics(boolean metricsEnabled, @Nullable java.util.function.Function<String,String> uriTagValue)
globalRegistry
under the name Metrics.HTTP_SERVER_PREFIX
.
uriTagValue
function receives the actual uri and returns the uri tag value
that will be used for the metrics with Metrics.URI
tag.
For example instead of using the actual uri "/users/1"
as uri tag value, templated uri
"/users/{id}"
can be used.
Note: It is strongly recommended applications to configure an upper limit for the number of the URI tags. For example:
Metrics.globalRegistry .config() .meterFilter(MeterFilter.maximumAllowableTags(HTTP_SERVER_PREFIX, URI, 100, MeterFilter.deny()));
By default metrics are not enabled.
metricsEnabled
- true enables metrics collection; false disables ituriTagValue
- a function that receives the actual uri and returns the uri tag value
that will be used for the metrics with Metrics.URI
tagHttpServer
@Deprecated public final HttpServer metrics(boolean metricsEnabled, HttpServerMetricsRecorder recorder)
metrics(boolean, Supplier)
HttpServer
.
All generated metrics are provided to the specified recorder.metricsEnabled
- if true enables the metrics on the server.recorder
- the HttpServerMetricsRecorder
HttpServer
public final HttpServer metrics(boolean metricsEnabled, java.util.function.Supplier<? extends HttpServerMetricsRecorder> recorder)
HttpServer
.
All generated metrics are provided to the specified recorder
which is only instantiated if metrics are being enabled.metricsEnabled
- if true enables the metrics on the server.recorder
- a supplier for the HttpServerMetricsRecorder
HttpServer
public final HttpServer metrics(boolean metricsEnabled, java.util.function.Supplier<? extends HttpServerMetricsRecorder> recorder, java.util.function.Function<String,String> uriValue)
HttpServer
.
All generated metrics are provided to the specified recorder
which is only instantiated if metrics are being enabled.
uriValue
function receives the actual uri and returns the uri value
that will be used when the metrics are propagated to the recorder.
For example instead of using the actual uri "/users/1"
as uri value, templated uri
"/users/{id}"
can be used.
metricsEnabled
- if true enables the metrics on the server.recorder
- a supplier for the HttpServerMetricsRecorder
uriValue
- a function that receives the actual uri and returns the uri value
that will be used when the metrics are propagated to the recorder.HttpServer
public final HttpServer host(String host)
host
- The host to bind to.HttpServer
public final HttpServer handle(java.util.function.BiFunction<? super HttpServerRequest,? super HttpServerResponse,? extends Publisher<Void>> handler)
handler
- an I/O handler that can dispose underlying connection when Publisher
terminates. Only the first registered handler will subscribe to the
returned Publisher
while other will immediately cancel given a same
Connection
HttpServer
public final HttpServer httpRequestDecoder(java.util.function.Function<HttpRequestDecoderSpec,HttpRequestDecoderSpec> requestDecoderOptions)
HttpServerCodec
's request decoding options.requestDecoderOptions
- a function to mutate the provided Http request decoder optionsHttpServer
public final HttpServer idleTimeout(java.time.Duration idleTimeout)
If an idleTimeout
is not specified, this indicates no timeout (i.e. infinite),
which means the connection will be closed only if one of the peers decides to close it.
If the idleTimeout
is less than 1ms
, then 1ms
will be the idle timeout.
By default idleTimeout
is not specified.
idleTimeout
- an idle timeout on the connection when it is waiting for an HTTP request (resolution: ms)HttpServer
public final HttpServer cookieCodec(ServerCookieEncoder encoder)
ServerCookieEncoder
; ServerCookieDecoder
will be
chosen based on the encoderencoder
- the preferred ServerCookieEncoderHttpServer
public final HttpServer cookieCodec(ServerCookieEncoder encoder, ServerCookieDecoder decoder)
ServerCookieEncoder
and ServerCookieDecoder
encoder
- the preferred ServerCookieEncoderdecoder
- the preferred ServerCookieDecoderHttpServer
public final HttpServer observe(ConnectionObserver observer)
Channel
has been connected and after it has been disconnected.observer
- a consumer observing state changesHttpServer
public final HttpServer protocol(HttpProtocol... supportedProtocols)
HttpProtocol.HTTP11
.supportedProtocols
- The various HttpProtocol
this server will supportHttpServer
public final HttpServer port(int port)
bind()
operation:port
- The port to bind to.HttpServer
public final HttpServer secure(java.util.function.Consumer<? super SslProvider.SslContextSpec> sslProviderBuilder)
SslContext
to be passed to with a default value of
10
seconds handshake timeout unless the environment property reactor.netty.tcp.sslHandshakeTimeout
is set.
If SelfSignedCertificate
needs to be used, the sample below can be
used. Note that SelfSignedCertificate
should not be used in production.
SelfSignedCertificate cert = new SelfSignedCertificate();
SslContextBuilder sslContextBuilder =
SslContextBuilder.forServer(cert.certificate(), cert.privateKey());
secure(sslContextSpec -> sslContextSpec.sslContext(sslContextBuilder));
sslProviderBuilder
- builder callback for further customization of SslContext
.HttpServer
public final HttpServer route(java.util.function.Consumer<? super HttpServerRoutes> routesBuilder)
HttpServerRoutes
builder.routesBuilder
- provides a route builder to be mutated in order to define routes.HttpServer
starting the router on subscribepublic final HttpServer tcpConfiguration(java.util.function.Function<? super TcpServer,? extends TcpServer> tcpMapper)
ServerBootstrap
configuration given mapper taking currently
configured one and returning a new one to be ultimately used for socket binding.
Configuration will apply during tcpConfiguration()
phase.
tcpMapper
- A TcpServer
mapping function to update tcp configuration and
return an enriched TCP server to use.HttpServer
public final HttpServer channelGroup(ChannelGroup channelGroup)
ChannelGroup
to hold all active connected channels. Effectively,
a shortcut for setting the same property on the underlying TcpServer
:
HttpServer.create()
.tcpConfiguration(server -> server.channelGroup(channelGroup))
Graceful Shutdown:
When a ChannelGroup
is set, calls to DisposableChannel.disposeNow()
and DisposableChannel.disposeNow(Duration)
not only stop accepting new requests
but also additionally wait for all active requests, in the ChannelGroup
, to
complete, within the given timeout.
channelGroup
- a ChannelGroup
HttpServer
TcpServer.channelGroup(ChannelGroup)
public final HttpServer wiretap(boolean enable)
HttpServer
category
and DEBUG
logger levelenable
- Specifies whether the wire logger configuration will be added to
the pipelineHttpServer
protected abstract Mono<? extends DisposableServer> bind(TcpServer b)
b
- the TcpServer
to bindMono
of DisposableServer