Class HttpServer
ServerTransport.bind()
is ultimately called.
Examples:
HttpServer.create()
.host("0.0.0.0")
.handle((req, res) -> res.sendString(Flux.just("hello")))
.bind()
.block();
- Author:
- Stephane Maldini, Violeta Georgieva
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionfinal HttpServer
accessLog
(boolean enable) Enable or disable the access log.final HttpServer
accessLog
(boolean enable, AccessLogFactory accessLogFactory) Enable or disable the access log and customize it through anAccessLogFactory
.final HttpServer
accessLog
(Function<AccessLogArgProvider, @Nullable AccessLog> accessLogFactory) Deprecated.as of 1.0.3.final HttpServer
bindAddress
(Supplier<? extends SocketAddress> bindAddressSupplier) Set a new local address to which this transport should bind on subscribe.final HttpServer
channelGroup
(ChannelGroup channelGroup) Provide aChannelGroup
to hold all active connected channels.final HttpServer
compress
(boolean compressionEnabled) Specifies whether GZip response compression is enabled if the client request presents accept encoding.final HttpServer
compress
(int minResponseSize) Enable GZip response compression if the client request presents accept encoding headers AND the response reaches a minimum threshold.final HttpServer
compress
(BiPredicate<HttpServerRequest, HttpServerResponse> predicate) Enable GZip response compression if the client request presents accept encoding headers and the providedPredicate
matches.final HttpServer
compressOptions
(HttpCompressionOption... compressionOptions) final HttpServer
cookieCodec
(ServerCookieEncoder encoder) Deprecated.as of 1.1.0.final HttpServer
cookieCodec
(ServerCookieEncoder encoder, ServerCookieDecoder decoder) Deprecated.as of 1.1.0.static HttpServer
create()
Prepare anHttpServer
.final HttpServer
errorLog
(boolean enable) Enable or disable the error log.final HttpServer
errorLog
(boolean enable, ErrorLogFactory errorLogFactory) Enable or disable the error log and customize it through anErrorLogFactory
.final HttpServer
forwarded
(boolean forwardedEnabled) Specifies whether support for the"Forwarded"
and"X-Forwarded-*"
HTTP request headers for deriving information about the connection is enabled.final HttpServer
Specifies a custom request handler for deriving information about the connection.static HttpServer
Deprecated.Use the other methods exposed byHttpServer
to achieve the same configurations.final HttpServer
handle
(BiFunction<? super HttpServerRequest, ? super HttpServerResponse, ? extends Publisher<Void>> handler) Attach an I/O handler to react on a connected client.final HttpServer
The host to which this server should bind.final HttpServer
http2Settings
(Consumer<Http2SettingsSpec.Builder> http2Settings) Apply HTTP/2 configuration.final HttpServer
http3Settings
(Consumer<Http3SettingsSpec.Builder> http3Settings) Apply HTTP/3 configuration.final HttpServer
httpFormDecoder
(Consumer<HttpServerFormDecoderProvider.Builder> formDecoderBuilder) Apply HTTP form decoder configuration.final HttpServer
httpMessageLogFactory
(HttpMessageLogFactory httpMessageLogFactory) WhenHttpMessage
is about to be logged the configured factory will be used for generating a sanitized log message.final HttpServer
httpRequestDecoder
(Function<HttpRequestDecoderSpec, HttpRequestDecoderSpec> requestDecoderOptions) Configure theHttpServerCodec
's request decoding options.final HttpServer
idleTimeout
(Duration idleTimeout) Specifies an idle timeout on the connection when it is waiting for an HTTP request (resolution: ms).final HttpServer
mapHandle
(BiFunction<? super Mono<Void>, ? super Connection, ? extends Mono<Void>> mapHandle) Decorate the configured I/O handler.final HttpServer
maxKeepAliveRequests
(int maxKeepAliveRequests) The maximum number of HTTP/1.1 requests which can be served until the connection is closed by the server.final HttpServer
Whether to enable metrics to be collected and registered in Micrometer'sglobalRegistry
under the nameMetrics.HTTP_SERVER_PREFIX
.final HttpServer
metrics
(boolean enable, Function<String, String> uriTagValue, Function<String, String> methodTagValue) Whether to enable metrics to be collected and registered in Micrometer'sglobalRegistry
under the nameMetrics.HTTP_SERVER_PREFIX
.final HttpServer
metrics
(boolean enable, Supplier<? extends ChannelMetricsRecorder> recorder) Specifies whether the metrics are enabled on theTransport
.final HttpServer
metrics
(boolean enable, Supplier<? extends ChannelMetricsRecorder> recorder, Function<String, String> uriValue) Specifies whether the metrics are enabled on theHttpServer
.final HttpServer
metrics
(boolean enable, Supplier<? extends ChannelMetricsRecorder> recorder, Function<String, String> uriValue, Function<String, String> methodValue) Specifies whether the metrics are enabled on theHttpServer
.final HttpServer
noSSL()
Removes any previously applied SSL configuration customization.final HttpServer
port
(int port) The port to which this server should bind.final HttpServer
protocol
(HttpProtocol... supportedProtocols) The HTTP protocol to support.final HttpServer
proxyProtocol
(ProxyProtocolSupportType proxyProtocolSupportType) Specifies whether support for the"HAProxy proxy protocol"
for deriving information about the address of the remote peer is enabled.final HttpServer
readTimeout
(@Nullable Duration readTimeout) Specifies the maximum duration allowed between each network-level read operation while reading a given request content (resolution: ms).final HttpServer
requestTimeout
(@Nullable Duration requestTimeout) Specifies the maximum duration for reading a given request content (resolution: ms).final HttpServer
route
(Consumer<? super HttpServerRoutes> routesBuilder) Define routes for the server through the providedHttpServerRoutes
builder.final HttpServer
secure
(Consumer<? super SslProvider.SslContextSpec> sslProviderBuilder) Apply an SSL configuration customization via the passed builder.final HttpServer
secure
(Consumer<? super SslProvider.SslContextSpec> sslProviderBuilder, boolean redirectHttpToHttps) Apply an SSL configuration customization via the passed builder.final HttpServer
secure
(SslProvider sslProvider) Applies an SSL configuration via the passedSslProvider
.final HttpServer
secure
(SslProvider sslProvider, boolean redirectHttpToHttps) Applies an SSL configuration via the passedSslProvider
.final HttpServer
tcpConfiguration
(Function<? super TcpServer, ? extends TcpServer> tcpMapper) Deprecated.Use the other methods exposed byHttpServer
to achieve the same configurations.warmup()
Based on the actual configuration, returns aMono
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, thebind operation
absorbs the extra time needed to load resources.final HttpServer
wiretap
(boolean enable) Apply or remove a wire logger configuration usingTransport
category (logger),DEBUG
logger level andAdvancedByteBufFormat.HEX_DUMP
forByteBuf
format, which means both events and content will be logged and the content will be in hex format.Methods inherited from class reactor.netty.transport.ServerTransport
bind, bindNow, bindNow, bindUntilJavaShutdown, childAttr, childObserve, childOption, doOnBind, doOnBound, doOnConnection, doOnUnbound
-
Constructor Details
-
HttpServer
public HttpServer()
-
-
Method Details
-
create
Prepare anHttpServer
.- Returns:
- a new
HttpServer
-
from
Deprecated.Use the other methods exposed byHttpServer
to achieve the same configurations. This method will be removed in version 1.1.0.Prepare anHttpServer
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)
- Returns:
- a new
HttpServer
-
accessLog
Enable or disable the access log. If enabled, the default log system will be used.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.
- Parameters:
enable
- enable or disable the access log- Returns:
- a new
HttpServer
- Since:
- 1.0.3
-
accessLog
Enable or disable the access log and customize it through anAccessLogFactory
.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 tofilter
some requests out of the access log. Note that this method takes precedence over the "reactor.netty.http.server.accessLogEnabled" system property.- Parameters:
enable
- enable or disable the access logaccessLogFactory
- theAccessLogFactory
that creates anAccessLog
given anAccessLogArgProvider
- Returns:
- a new
HttpServer
- Since:
- 1.0.3
-
accessLog
@Deprecated public final HttpServer accessLog(Function<AccessLogArgProvider, @Nullable AccessLog> accessLogFactory) Deprecated.as of 1.0.3. Prefer thevariant
with theAccessLogFactory
interface instead. This method will be removed in version 1.2.0.Customize the access log, provided access logging has been enabled through the "reactor.netty.http.server.accessLogEnabled" system property.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();
- Parameters:
accessLogFactory
- theFunction
that creates anAccessLog
given anAccessLogArgProvider
- Returns:
- a new
HttpServer
- Since:
- 1.0.1
-
bindAddress
Description copied from class:Transport
Set a new local address to which this transport should bind on subscribe.- Overrides:
bindAddress
in classTransport<HttpServer,
HttpServerConfig> - Parameters:
bindAddressSupplier
- A supplier of the address to bind to.- Returns:
- a new
Transport
-
channelGroup
Description copied from class:Transport
Provide aChannelGroup
to hold all active connected channels.Graceful Shutdown:
When a
ChannelGroup
is set, calls toDisposableChannel.disposeNow()
andDisposableChannel.disposeNow(Duration)
not only stop accepting new requests but also additionally wait for all active requests, in theChannelGroup
, to complete, within the given timeout.- Overrides:
channelGroup
in classTransport<HttpServer,
HttpServerConfig> - Parameters:
channelGroup
- aChannelGroup
- Returns:
- a new
Transport
reference
-
compress
Enable GZip response compression if the client request presents accept encoding headers and the providedPredicate
matches.Note: the passed
HttpServerRequest
andHttpServerResponse
should be considered read-only and the implement SHOULD NOT consume or write the request/response in this predicate.- Parameters:
predicate
- that returns true to compress the response.- Returns:
- a new
HttpServer
-
compress
Specifies whether GZip response compression is enabled if the client request presents accept encoding. Default compression level is 6.- Parameters:
compressionEnabled
- if true GZip response compression is enabled if the client request presents accept encoding, otherwise disabled.- Returns:
- a new
HttpServer
-
compress
Enable GZip response compression if the client request presents accept encoding headers AND the response reaches a minimum threshold.- Parameters:
minResponseSize
- compression is performed once response size exceeds the given value in bytes- Returns:
- a new
HttpServer
-
compressOptions
- Parameters:
compressionOptions
- configuresHttpCompressionOption
after enable compressHttpServer.create() .compress(true) .compressOptions( GzipOption.builder() .compressionLevel(6) .windowBits(15) .memoryLevel(8) .build(), ZstdOption.builder() .compressionLevel(3) .build() ) .bindNow();
- Returns:
- a new
HttpServer
- Since:
- 1.2.3
-
cookieCodec
Deprecated.as of 1.1.0. This will be removed in 2.0.0 as Netty 5 supports only strict validation.Configure theServerCookieEncoder
;ServerCookieDecoder
will be chosen based on the encoder.- Parameters:
encoder
- the preferred ServerCookieEncoder- Returns:
- a new
HttpServer
-
cookieCodec
@Deprecated public final HttpServer cookieCodec(ServerCookieEncoder encoder, ServerCookieDecoder decoder) Deprecated.as of 1.1.0. This will be removed in 2.0.0 as Netty 5 supports only strict validation.Configure theServerCookieEncoder
andServerCookieDecoder
.- Parameters:
encoder
- the preferred ServerCookieEncoderdecoder
- the preferred ServerCookieDecoder- Returns:
- a new
HttpServer
-
errorLog
Enable or disable the error log. If enabled, the default log system will be used.Example:
HttpServer.create() .port(8080) .route(r -> r.get("/hello", (req, res) -> res.header(CONTENT_TYPE, TEXT_PLAIN) .sendString(Mono.just("Hello World!")))) .errorLog(true) .bindNow() .onDispose() .block();
Note that this method takes precedence over the "reactor.netty.http.server.errorLogEnabled" system property. By default, error logs are formatted as
[{datetime}] [pid {pid}] [client {remote address}] {error message}
.- Parameters:
enable
- enable or disable the error log- Returns:
- a new
HttpServer
- Since:
- 1.2.6
-
errorLog
Enable or disable the error log and customize it through anErrorLogFactory
.Example:
HttpServer.create() .port(8080) .route(r -> r.get("/hello", (req, res) -> res.header(CONTENT_TYPE, TEXT_PLAIN) .sendString(Mono.just("Hello World!")))) .errorLog(true, ErrorLogFactory.createFilter( args -> args.cause() instanceof RuntimeException, args -> ErrorLog.create("host-name={}", args.httpServerInfos().hostName()))) .bindNow() .onDispose() .block();
The
ErrorLogFactory
class offers several helper methods to generate such a function, notably if one wants tofilter
some exceptions out of the error log.Note that this method takes precedence over the "reactor.netty.http.server.errorLogEnabled" system property.
- Parameters:
enable
- enable or disable the error logerrorLogFactory
- theErrorLogFactory
that creates anErrorLog
given anErrorLogArgProvider
- Returns:
- a new
HttpServer
- Since:
- 1.2.6
-
forwarded
Specifies a custom request handler for deriving information about the connection.- Parameters:
handler
- the forwarded header handler- Returns:
- a new
HttpServer
- Since:
- 0.9.12
-
forwarded
Specifies whether support for the"Forwarded"
and"X-Forwarded-*"
HTTP request headers for deriving information about the connection is enabled.- Parameters:
forwardedEnabled
- if true support for the"Forwarded"
and"X-Forwarded-*"
HTTP request headers for deriving information about the connection is enabled, otherwise disabled.- Returns:
- a new
HttpServer
- Since:
- 0.9.7
-
handle
public final HttpServer handle(BiFunction<? super HttpServerRequest, ? super HttpServerResponse, ? extends Publisher<Void>> handler) Attach an I/O handler to react on a connected client.- Parameters:
handler
- an I/O handler that can dispose underlying connection whenPublisher
terminates. Only the first registered handler will subscribe to the returnedPublisher
while other will immediately cancel given a sameConnection
- Returns:
- a new
HttpServer
-
host
Description copied from class:ServerTransport
The host to which this server should bind.- Overrides:
host
in classServerTransport<HttpServer,
HttpServerConfig> - Parameters:
host
- the host to bind to.- Returns:
- a new
ServerTransport
reference
-
http2Settings
Apply HTTP/2 configuration.- Parameters:
http2Settings
- configuresHttp2SettingsSpec
before requesting- Returns:
- a new
HttpServer
-
http3Settings
@Incubating public final HttpServer http3Settings(Consumer<Http3SettingsSpec.Builder> http3Settings) Apply HTTP/3 configuration.- Parameters:
http3Settings
- configuresHttp3SettingsSpec
before requesting- Returns:
- a new
HttpServer
- Since:
- 1.2.0
-
httpFormDecoder
public final HttpServer httpFormDecoder(Consumer<HttpServerFormDecoderProvider.Builder> formDecoderBuilder) Apply HTTP form decoder configuration. The configuration is used whenHttpServerRequest.receiveForm()
is invoked. When a specific configuration per request is neededHttpServerRequest.receiveForm(Consumer)
should be used.- Parameters:
formDecoderBuilder
-HttpServerFormDecoderProvider.Builder
for HTTP form decoder configuration- Returns:
- a new
HttpServer
- Since:
- 1.0.11
-
httpMessageLogFactory
WhenHttpMessage
is about to be logged the configured factory will be used for generating a sanitized log message.Default to
ReactorNettyHttpMessageLogFactory
:- hides the query from the uri
- hides the headers values
- only
DecoderException
message is presented
- Parameters:
httpMessageLogFactory
- the factory for generating the log message- Returns:
- a new
HttpServer
- Since:
- 1.0.24
-
httpRequestDecoder
public final HttpServer httpRequestDecoder(Function<HttpRequestDecoderSpec, HttpRequestDecoderSpec> requestDecoderOptions) Configure theHttpServerCodec
's request decoding options.- Parameters:
requestDecoderOptions
- a function to mutate the provided Http request decoder options- Returns:
- a new
HttpServer
-
idleTimeout
Specifies an idle timeout on the connection when it is waiting for an HTTP request (resolution: ms). Once the timeout is reached the connection will be closed.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 than1ms
, then1ms
will be the idle timeout.By default
idleTimeout
is not specified.- Parameters:
idleTimeout
- an idle timeout on the connection when it is waiting for an HTTP request (resolution: ms)- Returns:
- a new
HttpServer
- Since:
- 0.9.15
-
mapHandle
public final HttpServer mapHandle(BiFunction<? super Mono<Void>, ? super Connection, ? extends Mono<Void>> mapHandle) Decorate the configured I/O handler. Seehandle(BiFunction)
.- Parameters:
mapHandle
- ABiFunction
to decorate the configured I/O handler- Returns:
- a new
HttpServer
-
maxKeepAliveRequests
The maximum number of HTTP/1.1 requests which can be served until the connection is closed by the server. Setting this attribute to:- -1: The connection serves unlimited number of requests. It is up to the I/O handler to decide to close the connection. This is the default behaviour.
- 1: The connection is marked as non persistent and serves just one request.
- >1: The connection serves a number of requests up to the specified maximum number then the connection is closed by the server.
- Parameters:
maxKeepAliveRequests
- the maximum number of HTTP/1.1 requests which can be served until the connection is closed by the server- Returns:
- a new
HttpServer
- Since:
- 1.0.13
-
metrics
Whether to enable metrics to be collected and registered in Micrometer'sglobalRegistry
under the nameMetrics.HTTP_SERVER_PREFIX
.uriTagValue
function receives the actual uri and returns the uri tag value that will be used for the metrics withMetrics.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.
- Parameters:
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 withMetrics.URI
tag- Returns:
- a new
HttpServer
- Since:
- 0.9.7
-
metrics
public final HttpServer metrics(boolean enable, Function<String, String> uriTagValue, Function<String, String> methodTagValue) Whether to enable metrics to be collected and registered in Micrometer'sglobalRegistry
under the nameMetrics.HTTP_SERVER_PREFIX
.uriTagValue
function receives the actual uri and returns the uri tag value that will be used for the metrics withMetrics.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()));
methodTagValue
function receives the actual method name and returns the method tag value that will be used for the metrics withMetrics.METHOD
tag.By default metrics are not enabled.
- Parameters:
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 withMetrics.URI
tagmethodTagValue
- a function that receives the actual method name and returns the method tag value that will be used for the metrics withMetrics.METHOD
tag- Returns:
- a new
HttpServer
- Since:
- 1.0.39
-
metrics
public final HttpServer metrics(boolean enable, Supplier<? extends ChannelMetricsRecorder> recorder) Description copied from class:Transport
Specifies whether the metrics are enabled on theTransport
. 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 theTransport
).- Overrides:
metrics
in classTransport<HttpServer,
HttpServerConfig> - Parameters:
enable
- if true enables the metrics on theTransport
.recorder
- a supplier for theChannelMetricsRecorder
- Returns:
- a new
Transport
reference
-
metrics
public final HttpServer metrics(boolean enable, Supplier<? extends ChannelMetricsRecorder> recorder, Function<String, String> uriValue) Specifies whether the metrics are enabled on theHttpServer
. 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 theHttpServer
).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.- Parameters:
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.- Returns:
- a new
HttpServer
-
metrics
public final HttpServer metrics(boolean enable, Supplier<? extends ChannelMetricsRecorder> recorder, Function<String, String> uriValue, Function<String, String> methodValue) Specifies whether the metrics are enabled on theHttpServer
. 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 theHttpServer
).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.methodValue
function receives the actual method name and returns the method value that will be used when the metrics are propagated to the recorder.- Parameters:
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.methodValue
- a function that receives the actual method name and returns the method value that will be used when the metrics are propagated to the recorder.- Returns:
- a new
HttpServer
- Since:
- 1.0.39
-
noSSL
Removes any previously applied SSL configuration customization.- Returns:
- a new
HttpServer
-
port
The port to which this server should bind. If a port is not specified, the system picks up an ephemeral port.- Overrides:
port
in classServerTransport<HttpServer,
HttpServerConfig> - Parameters:
port
- The port to bind to.- Returns:
- a new
HttpServer
-
protocol
The HTTP protocol to support. Default isHttpProtocol.HTTP11
.- Parameters:
supportedProtocols
- The variousHttpProtocol
this server will support- Returns:
- a new
HttpServer
-
proxyProtocol
Specifies whether support for the"HAProxy proxy protocol"
for deriving information about the address of the remote peer is enabled.- Parameters:
proxyProtocolSupportType
--
choose
ProxyProtocolSupportType.ON
to enable support for the"HAProxy proxy protocol"
for deriving information about the address of the remote peer. - choose
ProxyProtocolSupportType.OFF
to disable the proxy protocol support. -
choose
ProxyProtocolSupportType.AUTO
then each connection of the sameHttpServer
will auto detect whether there is proxy protocol, soHttpServer
can accept requests with or without proxy protocol at the same time.
-
choose
- Returns:
- a new
HttpServer
-
readTimeout
Specifies the maximum duration allowed between each network-level read operation while reading a given request content (resolution: ms). In other words,ReadTimeoutHandler
is added to the channel pipeline after all the request headers are received, and removed from the channel pipeline after the content is fully received. If thereadTimeout
isnull
, any previous setting will be removed and noreadTimeout
will be applied. If thereadTimeout
is less than1ms
, then1ms
will be thereadTimeout
.- Parameters:
readTimeout
- the maximum duration allowed between each network-level read operation while reading a given request content (resolution: ms)- Returns:
- a new
HttpServer
- Since:
- 1.1.9
- See Also:
-
requestTimeout
Specifies the maximum duration for reading a given request content (resolution: ms). If therequestTimeout
isnull
, any previous setting will be removed and norequestTimeout
will be applied. If therequestTimeout
is less than1ms
, then1ms
will be therequestTimeout
.- Parameters:
requestTimeout
- the maximum duration for reading a given request content (resolution: ms)- Returns:
- a new
HttpServer
- Since:
- 1.1.9
-
route
Define routes for the server through the providedHttpServerRoutes
builder.- Parameters:
routesBuilder
- provides a route builder to be mutated in order to define routes.- Returns:
- a new
HttpServer
starting the router on subscribe
-
secure
Apply an SSL configuration customization via the passed builder. The builder will produce theSslContext
to be passed to with a default value of:10
seconds handshake timeout unless the environment propertyreactor.netty.tcp.sslHandshakeTimeout
is set.3
seconds close_notify flush timeout0
second close_notify read timeout
X509Bundle cert = new CertificateBuilder().subject("CN=localhost").setIsCertificateAuthority(true).buildSelfSigned(); Http11SslContextSpec http11SslContextSpec = Http11SslContextSpec.forServer(cert.toTempCertChainPem(), cert.toTempPrivateKeyPem()); secure(sslContextSpec -> sslContextSpec.sslContext(http11SslContextSpec));
- Parameters:
sslProviderBuilder
- builder callback for further customization of SslContext.- Returns:
- a new
HttpServer
-
secure
public final HttpServer secure(Consumer<? super SslProvider.SslContextSpec> sslProviderBuilder, boolean redirectHttpToHttps) Apply an SSL configuration customization via the passed builder. The builder will produce theSslContext
to be passed to with a default value of:10
seconds handshake timeout unless the environment propertyreactor.netty.tcp.sslHandshakeTimeout
is set.3
seconds close_notify flush timeout0
second close_notify read timeout
If self-signed certificate needs to be used, the sample below can be used (the functionality is provided by io.netty:netty-pkitesting). Note that self-signed certificate should not be used in production.
X509Bundle cert = new CertificateBuilder().subject("CN=localhost").setIsCertificateAuthority(true).buildSelfSigned(); Http11SslContextSpec http11SslContextSpec = Http11SslContextSpec.forServer(cert.toTempCertChainPem(), cert.toTempPrivateKeyPem()); secure(sslContextSpec -> sslContextSpec.sslContext(http11SslContextSpec), true);
- Parameters:
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.- Returns:
- a new
HttpServer
- Since:
- 1.0.5
-
secure
Applies an SSL configuration via the passedSslProvider
. If self-signed certificate needs to be used, the sample below can be used (the functionality is provided by io.netty:netty-pkitesting). Note that self-signed certificate should not be used in production.X509Bundle cert = new CertificateBuilder().subject("CN=localhost").setIsCertificateAuthority(true).buildSelfSigned(); Http11SslContextSpec http11SslContextSpec = Http11SslContextSpec.forServer(cert.toTempCertChainPem(), cert.toTempPrivateKeyPem()); secure(sslContextSpec -> sslContextSpec.sslContext(http11SslContextSpec));
- Parameters:
sslProvider
- The provider to set when configuring SSL- Returns:
- a new
HttpServer
-
secure
Applies an SSL configuration via the passedSslProvider
.If self-signed certificate needs to be used, the sample below can be used (the functionality is provided by io.netty:netty-pkitesting). Note that self-signed certificate should not be used in production.
X509Bundle cert = new CertificateBuilder().subject("CN=localhost").setIsCertificateAuthority(true).buildSelfSigned(); Http11SslContextSpec http11SslContextSpec = Http11SslContextSpec.forServer(cert.toTempCertChainPem(), cert.toTempPrivateKeyPem()); secure(sslContextSpec -> sslContextSpec.sslContext(http11SslContextSpec), true);
- Parameters:
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.- Returns:
- a new
HttpServer
- Since:
- 1.0.5
-
tcpConfiguration
@Deprecated public final HttpServer tcpConfiguration(Function<? super TcpServer, ? extends TcpServer> tcpMapper) Deprecated.Use the other methods exposed byHttpServer
to achieve the same configurations. This method will be removed in version 1.1.0.Apply aTcpServer
mapping function to update TCP configuration and return an enrichedHttpServer
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)
- Parameters:
tcpMapper
- ATcpServer
mapping function to update TCP configuration and return an enrichedHttpServer
to use.- Returns:
- a new
HttpServer
-
warmup
Based on the actual configuration, returns aMono
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
bind operation
absorbs the extra time needed to load resources.- Overrides:
warmup
in classServerTransport<HttpServer,
HttpServerConfig> - Returns:
- a
Mono
representing the completion of the warmup - Since:
- 1.0.3
-
wiretap
Description copied from class:Transport
Apply or remove a wire logger configuration usingTransport
category (logger),DEBUG
logger level andAdvancedByteBufFormat.HEX_DUMP
forByteBuf
format, which means both events and content will be logged and the content will be in hex format.- Overrides:
wiretap
in classTransport<HttpServer,
HttpServerConfig> - Parameters:
enable
- specifies whether the wire logger configuration will be added to the pipeline- Returns:
- a new
Transport
reference
-