public abstract class HttpServer extends ServerTransport<HttpServer,HttpServerConfig>
ServerTransport.bind() is ultimately called.
Examples:
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 |
|---|---|
HttpServer |
accessLog(boolean enable)
Enable or disable the access log.
|
HttpServer |
accessLog(boolean enable,
AccessLogFactory accessLogFactory)
Enable or disable the access log and customize it through an
AccessLogFactory. |
HttpServer |
accessLog(Function<AccessLogArgProvider,AccessLog> accessLogFactory)
Deprecated.
as of 1.0.3. Prefer the
variant
with the AccessLogFactory interface instead. This method will be removed in version 1.2.0. |
HttpServer |
bindAddress(Supplier<? extends SocketAddress> bindAddressSupplier)
Set a new local address to which this transport should bind on subscribe.
|
HttpServer |
channelGroup(ChannelGroup channelGroup)
Provide a
ChannelGroup to hold all active connected channels. |
HttpServer |
compress(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 is enabled if the client request
presents accept encoding.
|
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(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)
Deprecated.
Use the other methods exposed by
HttpServer to achieve the same configurations.
This method will be removed in version 1.1.0. |
HttpServer |
handle(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 |
http2Settings(Consumer<Http2SettingsSpec.Builder> http2Settings)
Apply HTTP/2 configuration
|
HttpServer |
httpFormDecoder(Consumer<HttpServerFormDecoderProvider.Builder> formDecoderBuilder)
Apply HTTP form decoder configuration.
|
HttpServer |
httpMessageLogFactory(HttpMessageLogFactory httpMessageLogFactory)
When
HttpMessage is about to be logged the configured factory will be used for
generating a sanitized log message. |
HttpServer |
httpRequestDecoder(Function<HttpRequestDecoderSpec,HttpRequestDecoderSpec> requestDecoderOptions)
Configure the
HttpServerCodec's request decoding options. |
HttpServer |
idleTimeout(Duration idleTimeout)
Specifies an idle timeout on the connection when it is waiting for an HTTP request (resolution: ms).
|
HttpServer |
mapHandle(BiFunction<? super Mono<Void>,? super Connection,? extends Mono<Void>> mapHandle)
Decorate the configured I/O handler.
|
HttpServer |
maxKeepAliveRequests(int maxKeepAliveRequests)
The maximum number of HTTP/1.1 requests which can be served until the connection is closed by the server.
|
HttpServer |
metrics(boolean enable,
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 enable,
Supplier<? extends ChannelMetricsRecorder> recorder)
Specifies whether the metrics are enabled on the
Transport. |
HttpServer |
metrics(boolean enable,
Supplier<? extends ChannelMetricsRecorder> recorder,
Function<String,String> uriValue)
Specifies whether the metrics are enabled on the
HttpServer. |
HttpServer |
noSSL()
Removes any previously applied SSL configuration customization
|
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(Consumer<? super HttpServerRoutes> routesBuilder)
Define routes for the server through the provided
HttpServerRoutes builder. |
HttpServer |
secure(Consumer<? super SslProvider.SslContextSpec> sslProviderBuilder)
Apply an SSL configuration customization via the passed builder.
|
HttpServer |
secure(Consumer<? super SslProvider.SslContextSpec> sslProviderBuilder,
boolean redirectHttpToHttps)
Apply an SSL configuration customization via the passed builder.
|
HttpServer |
secure(SslProvider sslProvider)
Applies an SSL configuration via the passed
SslProvider. |
HttpServer |
secure(SslProvider sslProvider,
boolean redirectHttpToHttps)
Applies an SSL configuration via the passed
SslProvider. |
HttpServer |
tcpConfiguration(Function<? super TcpServer,? extends TcpServer> tcpMapper)
Deprecated.
Use the other methods exposed by
HttpServer to achieve the same configurations.
This method will be removed in version 1.1.0. |
Mono<Void> |
warmup()
Based on the actual configuration, returns a
Mono that triggers:
an initialization of the event loop groups
loads the necessary native libraries for the transport
loads the necessary native libraries for the security if there is such
By default, when method is not used, the bind operation absorbs the extra time needed to load resources. |
HttpServer |
wiretap(boolean enable)
Apply or remove a wire logger configuration using
Transport category (logger),
DEBUG logger level and AdvancedByteBufFormat.HEX_DUMP for ByteBuf format,
which means both events and content will be logged and the content will be in hex format. |
bind, bindNow, bindNow, bindUntilJavaShutdown, childAttr, childObserve, childOption, doOnBind, doOnBound, doOnConnection, doOnUnboundpublic static HttpServer create()
HttpServerHttpServer@Deprecated public static HttpServer from(TcpServer tcpServer)
HttpServer to achieve the same configurations.
This method will be removed in version 1.1.0.HttpServer
Note:
There isn't only one method that replaces this deprecated method.
The configuration that can be done with this deprecated method,
can also be done with the other methods exposed by HttpServer.
Examples:
Configuration via the deprecated '.from(...)' method
HttpServer.from(
TcpServer.attr(...) // configures the channel attributes
.bindAddress(...) // configures the bind (local) address
.childAttr(...) // configures the child channel attributes
.childObserve() // configures the child channel connection observer
.childOption(...) // configures the child channel options
.channelGroup(...) // configures the channel group
.doOnBound(...) // configures the doOnBound callback
.doOnChannelInit(...) // configures the channel handler
.doOnConnection(...) // configures the doOnConnection callback
.doOnUnbound(...) // configures the doOnUnbound callback
.metrics(...) // configures the metrics
.observe() // configures the connection observer
.option(...) // configures the channel options
.runOn(...) // configures the event loop group
.secure() // configures the SSL
.wiretap()) // configures the wire logging
Configuration via the other methods exposed by HttpServer
HttpServer.attr(...) // configures the channel attributes
.bindAddress(...) // configures the bind (local) address
.childAttr(...) // configures the child channel attributes
.childObserve() // configures the child channel connection observer
.childOption(...) // configures the child channel options
.channelGroup(...) // configures the channel group
.doOnBound(...) // configures the doOnBound callback
.doOnChannelInit(...) // configures the channel handler
.doOnConnection(...) // configures the doOnConnection callback
.doOnUnbound(...) // configures the doOnUnbound callback
.metrics(...) // configures the metrics
.observe() // configures the connection observer
.option(...) // configures the channel options
.runOn(...) // configures the event loop group
.secure() // configures the SSL
.wiretap() // configures the wire logging
Wire logging in plain text
HttpServer.wiretap("logger", LogLevel.DEBUG, AdvancedByteBufFormat.TEXTUAL)
HttpServerpublic final HttpServer accessLog(boolean enable)
Example:
HttpServer.create()
.port(8080)
.route(r -> r.get("/hello",
(req, res) -> res.header(CONTENT_TYPE, TEXT_PLAIN)
.sendString(Mono.just("Hello World!"))))
.accessLog(true)
.bindNow()
.onDispose()
.block();
Note that this method takes precedence over the "reactor.netty.http.server.accessLogEnabled" system property.
enable - enable or disable the access logHttpServerpublic final HttpServer accessLog(boolean enable, AccessLogFactory accessLogFactory)
AccessLogFactory.
Example:
HttpServer.create()
.port(8080)
.route(r -> r.get("/hello",
(req, res) -> res.header(CONTENT_TYPE, TEXT_PLAIN)
.sendString(Mono.just("Hello World!"))))
.accessLog(true, AccessLogFactory.createFilter(
args -> String.valueOf(args.uri()).startsWith("/health"),
args -> AccessLog.create("user-agent={}", args.requestHeader("user-agent"))
)
.bindNow()
.onDispose()
.block();
The AccessLogFactory class offers several helper methods to generate such a function,
notably if one wants to filter some requests out of the access log.
Note that this method takes precedence over the "reactor.netty.http.server.accessLogEnabled" system property.
enable - enable or disable the access logaccessLogFactory - the AccessLogFactory that creates an AccessLog given an AccessLogArgProviderHttpServer@Deprecated public final HttpServer accessLog(Function<AccessLogArgProvider,AccessLog> accessLogFactory)
variant
with the AccessLogFactory interface instead. This method will be removed in version 1.2.0.Example:
HttpServer.create()
.port(8080)
.route(r -> r.get("/hello",
(req, res) -> res.header(CONTENT_TYPE, TEXT_PLAIN)
.sendString(Mono.just("Hello World!"))))
.accessLog(argProvider ->
AccessLog.create("user-agent={}", argProvider.requestHeader("user-agent")))
.bindNow()
.onDispose()
.block();
accessLogFactory - the Function that creates an AccessLog given an AccessLogArgProviderHttpServerpublic final HttpServer bindAddress(Supplier<? extends SocketAddress> bindAddressSupplier)
TransportbindAddress in class Transport<HttpServer,HttpServerConfig>bindAddressSupplier - A supplier of the address to bind to.Transportpublic final HttpServer channelGroup(ChannelGroup channelGroup)
TransportChannelGroup to hold all active connected channels.
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 in class Transport<HttpServer,HttpServerConfig>channelGroup - a ChannelGroupTransport referencepublic final HttpServer compress(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.HttpServerpublic final HttpServer compress(boolean compressionEnabled)
compressionEnabled - if true GZip response compression
is enabled if the client request presents accept encoding, otherwise disabled.HttpServerpublic final HttpServer compress(int minResponseSize)
minResponseSize - compression is performed once response size exceeds the given
value in bytesHttpServerpublic final HttpServer cookieCodec(ServerCookieEncoder encoder)
ServerCookieEncoder; ServerCookieDecoder will be
chosen based on the encoderencoder - the preferred ServerCookieEncoderHttpServerpublic final HttpServer cookieCodec(ServerCookieEncoder encoder, ServerCookieDecoder decoder)
ServerCookieEncoder and ServerCookieDecoderencoder - the preferred ServerCookieEncoderdecoder - the preferred ServerCookieDecoderHttpServerpublic final HttpServer forwarded(BiFunction<ConnectionInfo,HttpRequest,ConnectionInfo> handler)
handler - the forwarded header handlerHttpServerpublic 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.HttpServerpublic final HttpServer handle(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
ConnectionHttpServerpublic final HttpServer host(String host)
ServerTransporthost in class ServerTransport<HttpServer,HttpServerConfig>host - the host to bind to.ServerTransport referencepublic final HttpServer http2Settings(Consumer<Http2SettingsSpec.Builder> http2Settings)
http2Settings - configures Http2SettingsSpec before requestingHttpServerpublic final HttpServer httpFormDecoder(Consumer<HttpServerFormDecoderProvider.Builder> formDecoderBuilder)
HttpServerRequest.receiveForm() is invoked.
When a specific configuration per request is needed HttpServerRequest.receiveForm(Consumer)
should be used.formDecoderBuilder - HttpServerFormDecoderProvider.Builder for HTTP form decoder configurationHttpServerpublic final HttpServer httpMessageLogFactory(HttpMessageLogFactory httpMessageLogFactory)
HttpMessage is about to be logged the configured factory will be used for
generating a sanitized log message.
Default to ReactorNettyHttpMessageLogFactory:
DecoderException message is presentedhttpMessageLogFactory - the factory for generating the log messageHttpServerpublic final HttpServer httpRequestDecoder(Function<HttpRequestDecoderSpec,HttpRequestDecoderSpec> requestDecoderOptions)
HttpServerCodec's request decoding options.requestDecoderOptions - a function to mutate the provided Http request decoder optionsHttpServerpublic final HttpServer idleTimeout(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)HttpServerpublic final HttpServer mapHandle(BiFunction<? super Mono<Void>,? super Connection,? extends Mono<Void>> mapHandle)
handle(BiFunction).mapHandle - A BiFunction to decorate the configured I/O handlerHttpServerpublic final HttpServer maxKeepAliveRequests(int maxKeepAliveRequests)
maxKeepAliveRequests - the maximum number of HTTP/1.1 requests which can be served until
the connection is closed by the serverHttpServerpublic final HttpServer metrics(boolean enable, 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 to provide template-like form for the URIs. Without a conversion to a template-like form, each distinct URI leads to the creation of a distinct tag, which takes a lot of memory for the metrics.
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.
enable - 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 tagHttpServerpublic final HttpServer metrics(boolean enable, Supplier<? extends ChannelMetricsRecorder> recorder)
TransportTransport.
All generated metrics are provided to the specified recorder
which is only instantiated if metrics are being enabled (the instantiation is not lazy,
but happens immediately, while configuring the Transport).metrics in class Transport<HttpServer,HttpServerConfig>enable - if true enables the metrics on the Transport.recorder - a supplier for the ChannelMetricsRecorderTransport referencepublic final HttpServer metrics(boolean enable, Supplier<? extends ChannelMetricsRecorder> recorder, Function<String,String> uriValue)
HttpServer.
All generated metrics are provided to the specified recorder which is only
instantiated if metrics are being enabled (the instantiation is not lazy,
but happens immediately, while configuring the HttpServer).
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.
enable - true enables metrics collection; false disables itrecorder - a supplier for the metrics recorder that receives the collected metricsuriValue - a function that receives the actual uri and returns the uri value
that will be used when the metrics are propagated to the recorder.HttpServerpublic final HttpServer noSSL()
HttpServerpublic final HttpServer port(int port)
ServerTransportport in class ServerTransport<HttpServer,HttpServerConfig>port - The port to bind to.ServerTransport referencepublic final HttpServer protocol(HttpProtocol... supportedProtocols)
HttpProtocol.HTTP11.supportedProtocols - The various HttpProtocol this server will supportHttpServerpublic 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.
HttpServerpublic final HttpServer route(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 secure(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();
Http11SslContextSpec http11SslContextSpec =
Http11SslContextSpec.forServer(cert.certificate(), cert.privateKey());
secure(sslContextSpec -> sslContextSpec.sslContext(http11SslContextSpec));
sslProviderBuilder - builder callback for further customization of SslContext.HttpServerpublic final HttpServer secure(Consumer<? super SslProvider.SslContextSpec> sslProviderBuilder, boolean redirectHttpToHttps)
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();
Http11SslContextSpec http11SslContextSpec =
Http11SslContextSpec.forServer(cert.certificate(), cert.privateKey());
secure(sslContextSpec -> sslContextSpec.sslContext(http11SslContextSpec), true);
sslProviderBuilder - builder callback for further customization of SslContext.redirectHttpToHttps - true enables redirecting HTTP to HTTPS by changing the
scheme only but otherwise leaving the port the same.
This configuration is applicable only for HTTP 1.x.HttpServerpublic final HttpServer secure(SslProvider sslProvider)
SslProvider.
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();
Http11SslContextSpec http11SslContextSpec =
Http11SslContextSpec.forServer(cert.certificate(), cert.privateKey());
secure(sslContextSpec -> sslContextSpec.sslContext(http11SslContextSpec));
sslProvider - The provider to set when configuring SSLHttpServerpublic final HttpServer secure(SslProvider sslProvider, boolean redirectHttpToHttps)
SslProvider.
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();
Http11SslContextSpec http11SslContextSpec =
Http11SslContextSpec.forServer(cert.certificate(), cert.privateKey());
secure(sslContextSpec -> sslContextSpec.sslContext(http11SslContextSpec), true);
sslProvider - The provider to set when configuring SSLredirectHttpToHttps - true enables redirecting HTTP to HTTPS by changing the
scheme only but otherwise leaving the port the same.
This configuration is applicable only for HTTP 1.x.HttpServer@Deprecated public final HttpServer tcpConfiguration(Function<? super TcpServer,? extends TcpServer> tcpMapper)
HttpServer to achieve the same configurations.
This method will be removed in version 1.1.0.TcpServer mapping function to update TCP configuration and
return an enriched HttpServer to use.
Note:
There isn't only one method that replaces this deprecated method.
The configuration that can be done with this deprecated method,
can also be done with the other methods exposed by HttpServer.
Examples:
Configuration via the deprecated '.tcpConfiguration(...)' method
HttpServer.tcpConfiguration(tcpServer ->
tcpServer.attr(...) // configures the channel attributes
.bindAddress(...) // configures the bind (local) address
.channelGroup(...) // configures the channel group
.childAttr(...) // configures the child channel attributes
.childObserve(...) // configures the child channel connection observer
.childOption(...) // configures the child channel options
.doOnBound(...) // configures the doOnBound callback
.doOnChannelInit(...) // configures the channel handler
.doOnConnection(...) // configures the doOnConnection callback
.doOnUnbound(...) // configures the doOnUnbound callback
.handle(...) // configures the I/O handler
.host(...) // configures the host name
.metrics(...) // configures the metrics
.noSSL() // removes SSL configuration
.observe() // configures the connection observer
.option(...) // configures the channel options
.port(...) // configures the port
.runOn(...) // configures the event loop group
.secure() // configures the SSL
.wiretap()) // configures the wire logging
Configuration via the other methods exposed by HttpServer
HttpServer.attr(...) // configures the channel attributes
.bindAddress(...) // configures the bind (local) address
.channelGroup(...) // configures the channel group
.childAttr(...) // configures the child channel attributes
.childObserve(...) // configures the child channel connection observer
.childOption(...) // configures the child channel options
.doOnBound(...) // configures the doOnBound callback
.doOnChannelInit(...) // configures the channel handler
.doOnConnection(...) // configures the doOnConnection callback
.doOnUnbound(...) // configures the doOnUnbound callback
.handle(...) // configures the I/O handler
.host(...) // configures the host name
.metrics(...) // configures the metrics
.noSSL() // removes SSL configuration
.observe() // configures the connection observer
.option(...) // configures the channel options
.port(...) // configures the port
.runOn(...) // configures the event loop group
.secure() // configures the SSL
.wiretap() // configures the wire logging
Wire logging in plain text
HttpServer.wiretap("logger", LogLevel.DEBUG, AdvancedByteBufFormat.TEXTUAL)
tcpMapper - A TcpServer mapping function to update TCP configuration and
return an enriched HttpServer to use.HttpServerpublic Mono<Void> warmup()
Mono that triggers:
bind operation absorbs the extra time needed to load resources.warmup in class ServerTransport<HttpServer,HttpServerConfig>Mono representing the completion of the warmuppublic final HttpServer wiretap(boolean enable)
TransportTransport category (logger),
DEBUG logger level and AdvancedByteBufFormat.HEX_DUMP for ByteBuf format,
which means both events and content will be logged and the content will be in hex format.wiretap in class Transport<HttpServer,HttpServerConfig>enable - specifies whether the wire logger configuration will be added to the pipelineTransport reference