Skip to content

Instantly share code, notes, and snippets.

@ptomaszek
Last active January 9, 2021 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptomaszek/c2f621d6c6984def0feb930a914a58de to your computer and use it in GitHub Desktop.
Save ptomaszek/c2f621d6c6984def0feb930a914a58de to your computer and use it in GitHub Desktop.
Vertx 3.9 - HTTP/2 Server and Client
//curl --write-out --http2 --insecure https://localhost:8083
import io.vertx.core.Vertx
import io.vertx.core.http.HttpServerOptions
import io.vertx.core.net.PemKeyCertOptions
def vertx = Vertx.vertx()
vertx
.createHttpServer(new HttpServerOptions()
.setPemKeyCertOptions( //openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem
new PemKeyCertOptions()
.setKeyPath('key.pem')
.setCertPath('cert.pem')
)
.setUseAlpn(true)
.setSsl(true)
)
.requestHandler { req ->
vertx.setTimer(500) {
req.response().end("OK " + req.version())
println('Replied after short delay!')
}
}
.listen(8083)
//curl --silent --write-out "\n" http://localhost:8081?callsToMake=100 | json_pp
import io.netty.handler.codec.http.HttpHeaderValues
import io.vertx.core.CompositeFuture
import io.vertx.core.Future
import io.vertx.core.Vertx
import io.vertx.core.http.HttpHeaders
import io.vertx.core.http.HttpVersion
import io.vertx.core.json.JsonObject
import io.vertx.ext.web.client.WebClient
import io.vertx.ext.web.client.WebClientOptions
import java.time.Instant
def vertx = Vertx.vertx()
def http2Client = WebClient.create(vertx,
new WebClientOptions()
.setProtocolVersion(HttpVersion.HTTP_2)
.setSsl(true)
.setUseAlpn(true)
.setTrustAll(true)
.setVerifyHost(false)
)
vertx.createHttpServer()
.requestHandler { req ->
def start = Instant.now()
def callsToMake = req.getParam('callsToMake') as Integer
CompositeFuture.all(
(1..callsToMake).collect { callNo ->
Future.future { promise ->
http2Client.get(8083, 'localhost', '/').send { resp ->
if (resp.succeeded()) {
def httpVersion = resp.result().version()
println "HTTP version: ${httpVersion}"
promise.complete(httpVersion)
} else {
promise.fail(resp.cause() as Throwable)
}
}
}
}
).onSuccess {
def end = Instant.now()
req.response()
.putHeader(HttpHeaders.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON)
.end(([
callsCount: it.size(),
timeMs : end.toEpochMilli() - start.toEpochMilli(),
httpTypes : it.result().list().unique()
] as JsonObject).toString())
}.onFailure {
println it.message
req.response().end(it.message)
}
}
.listen(8081)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment