Skip to content

Commit

Permalink
Demonstrate multi-address client in HTTP examples (#2709)
Browse files Browse the repository at this point in the history
Motivation:
Some HTTP examples only use single-address client. It would be helpful to also provide multi-address client examples.

Modification:
- Create `RetryUrlClient`
- Create `TimeoutUrlClient`
- Create `LifecycleObserverUrlClient `
- Create `CompressionFilterExampleUrlClient `

Result:
Both single-address and multi-address clients are demonstrated in HTTP examples.
  • Loading branch information
sonicloong authored Sep 22, 2023
1 parent 9bc9746 commit e123616
Show file tree
Hide file tree
Showing 7 changed files with 264 additions and 6 deletions.
15 changes: 12 additions & 3 deletions servicetalk-examples/docs/modules/ROOT/pages/http/index.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,10 @@ needed for the other API variants as the usage of content encoding filters is th

* link:{source-root}/servicetalk-examples/http/compression/src/main/java/io/servicetalk/examples/http/compression/CompressionFilterExampleServer.java[CompressionFilterExampleServer] - a server that demonstrates
the asynchronous API and responds with a simple `Hello World!` response body, optionally customized for a specific name for `POST` requests, as a `text/plain`.
* link:{source-root}/servicetalk-examples/http/compression/src/main/java/io/servicetalk/examples/http/compression/CompressionFilterExampleClient.java[CompressionFilterExampleClient.java] - a client that
* link:{source-root}/servicetalk-examples/http/compression/src/main/java/io/servicetalk/examples/http/compression/CompressionFilterExampleClient.java[CompressionFilterExampleClient.java] - a single-address client that
sends a `POST` request containing a name to the link:{source-root}/servicetalk-examples/http/compression/src/main/java/io/servicetalk/examples/http/compression/CompressionFilterExampleServer.java[server] and
receives a response greeting the posted name as a single content.
* link:{source-root}/servicetalk-examples/http/compression/src/main/java/io/servicetalk/examples/http/compression/CompressionFilterExampleUrlClient.java[CompressionFilterExampleUrlClient.java] - a multi-address client that
sends a `POST` request containing a name to the link:{source-root}/servicetalk-examples/http/compression/src/main/java/io/servicetalk/examples/http/compression/CompressionFilterExampleServer.java[server] and
receives a response greeting the posted name as a single content.

Expand All @@ -101,7 +104,8 @@ Extends the async "Hello World" example to demonstrate the use of timeout filter
needed for the other API variants as the usage of the timeout features are the same for all API styles.

* link:{source-root}/servicetalk-examples/http/timeout/src/main/java/io/servicetalk/examples/http/timeout/TimeoutServer.java[TimeoutServer] - the async `Hello World!` server client enhanced to use timeout capabilities.
* link:{source-root}/servicetalk-examples/http/timeout/src/main/java/io/servicetalk/examples/http/timeout/TimeoutClient.java[TimeoutClient.java] - the async `Hello World!` client enhanced to use timeout capabilities.
* link:{source-root}/servicetalk-examples/http/timeout/src/main/java/io/servicetalk/examples/http/timeout/TimeoutClient.java[TimeoutClient.java] - the async `Hello World!` single-address client enhanced to use timeout capabilities.
* link:{source-root}/servicetalk-examples/http/timeout/src/main/java/io/servicetalk/examples/http/timeout/TimeoutUrlClient.java[TimeoutUrlClient.java] - the async `Hello World!` multi-address client enhanced to use timeout capabilities.

[#SerializationJson]
== Serialization: JSON
Expand Down Expand Up @@ -215,7 +219,10 @@ Using the following classes:
- link:{source-root}/servicetalk-examples/http/observer/src/main/java/io/servicetalk/examples/http/observer/LifecycleObserverServer.java[LifecycleObserverServer] - A server that installs a
link:{source-root}/servicetalk-http-api/src/main/java/io/servicetalk/http/api/HttpLifecycleObserver.java[HttpLifecycleObserver]
on the server builder.
- link:{source-root}/servicetalk-examples/http/observer/src/main/java/io/servicetalk/examples/http/observer/LifecycleObserverClient.java[LifecycleObserverClient] - A client that installs a
- link:{source-root}/servicetalk-examples/http/observer/src/main/java/io/servicetalk/examples/http/observer/LifecycleObserverClient.java[LifecycleObserverClient] - A single-address client that installs a
link:{source-root}/servicetalk-http-api/src/main/java/io/servicetalk/http/api/HttpLifecycleObserver.java[HttpLifecycleObserver]
on via a client filter on the client builder.
- link:{source-root}/servicetalk-examples/http/observer/src/main/java/io/servicetalk/examples/http/observer/LifecycleObserverUrlClient.java[LifecycleObserverUrlClient] - A multi-address client that installs a
link:{source-root}/servicetalk-http-api/src/main/java/io/servicetalk/http/api/HttpLifecycleObserver.java[HttpLifecycleObserver]
on via a client filter on the client builder.

Expand Down Expand Up @@ -266,6 +273,8 @@ A special "flaky" `Hello World` server that alternates "509" Gateway Timeout and
requests to demonstrate client retry.
* link:{source-root}/servicetalk-examples/http/retry/src/main/java/io/servicetalk/examples/http/retry/RetryClient.java[RetryClient.java] -
Async `Hello World` example that demonstrates how retry can be requested for a single-address client.
* link:{source-root}/servicetalk-examples/http/retry/src/main/java/io/servicetalk/examples/http/retry/RetryUrlClient.java[RetryUrlClient.java] -
Async `Hello World` example that demonstrates how retry can be requested for a multi-address client.


[#HTTP2]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import static io.servicetalk.http.api.HttpSerializers.textSerializerUtf8;

/**
* Extends the async "Hello World" example to include compression of the request and response bodies.
* Extends the async "Hello World" single-address example to include compression of the request and response bodies.
*/
public final class CompressionFilterExampleClient {
public static void main(String... args) throws Exception {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright © 2023 Apple Inc. and the ServiceTalk project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicetalk.examples.http.compression;

import io.servicetalk.concurrent.api.Single;
import io.servicetalk.encoding.api.BufferDecoderGroupBuilder;
import io.servicetalk.http.api.ContentEncodingHttpRequesterFilter;
import io.servicetalk.http.api.HttpClient;
import io.servicetalk.http.api.HttpRequest;
import io.servicetalk.http.api.HttpResponse;
import io.servicetalk.http.netty.HttpClients;

import static io.servicetalk.encoding.api.Identity.identityEncoder;
import static io.servicetalk.encoding.netty.NettyBufferEncoders.deflateDefault;
import static io.servicetalk.encoding.netty.NettyBufferEncoders.gzipDefault;
import static io.servicetalk.http.api.HttpSerializers.textSerializerUtf8;

/**
* Extends the async "Hello World" multi-address example to include compression of the request and response bodies.
*/
public class CompressionFilterExampleUrlClient {
public static void main(String... args) throws Exception {
try (HttpClient client = HttpClients.forMultiAddressUrl().initializer((scheme, address, builder) -> {
// Adds filter that provides compression for the request body when a request sets the encoding.
// Also sets the accept encoding header for the server's response.
// If necessary, users can set different filters based on `scheme` and/or `address`.
builder.appendClientFilter(new ContentEncodingHttpRequesterFilter(new BufferDecoderGroupBuilder()
// For the purposes of this example we disable GZip compression and use the
// server's second choice (deflate) to demonstrate that negotiation of compression algorithm is
// handled correctly.
// .add(NettyBufferEncoders.gzipDefault())
.add(deflateDefault())
.add(identityEncoder(), false).build()));
}).build()) {
// Make a request with an uncompressed payload.
HttpRequest request = client.post("http://localhost:8080/sayHello1")
// Request will be sent with no compression, same effect as setting encoding to identity
.contentEncoding(identityEncoder())
.payloadBody("World1", textSerializerUtf8());
Single<HttpResponse> respSingle1 = client.request(request)
.whenOnSuccess(resp -> {
System.out.println(resp.toString((name, value) -> value));
System.out.println(resp.payloadBody(textSerializerUtf8()));
});

// Make a request with an gzip compressed payload.
request = client.post("http://localhost:8080/sayHello2")
// Encode the request using gzip.
.contentEncoding(gzipDefault())
.payloadBody("World2", textSerializerUtf8());
Single<HttpResponse> respSingle2 = client.request(request)
.whenOnSuccess(resp -> {
System.out.println(resp.toString((name, value) -> value));
System.out.println(resp.payloadBody(textSerializerUtf8()));
});

// Issue the requests sequentially with concat.
respSingle1.concat(respSingle2)
// This example is demonstrating asynchronous execution, but needs to prevent the main thread from exiting
// before the response has been processed. This isn't typical usage for an asynchronous API but is useful
// for demonstration purposes.
.toFuture().get();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@
import static io.servicetalk.logging.api.LogLevel.TRACE;

/**
* An example client that shows {@link HttpLifecycleObserver} usage.
* An example singl-address client that shows {@link HttpLifecycleObserver} usage.
*/
public final class LifecycleObserverClient {
public static void main(String[] args) throws Exception {
// Note: this example demonstrates only blocking-aggregated programming paradigm, for asynchronous and
// streaming API see helloworld examples.
try (BlockingHttpClient client = HttpClients.forSingleAddress("localhost", 8080)
// Append this filter first for most cases to maximize visibility!
// See javadocs on GrpcLifecycleObserverRequesterFilter for more details on filter ordering.
// See javadocs on HttpLifecycleObserverRequesterFilter for more details on filter ordering.
.appendClientFilter(new HttpLifecycleObserverRequesterFilter(
HttpLifecycleObservers.logging("servicetalk-examples-http-observer-logger", TRACE)))
.buildBlocking()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Copyright © 2023 Apple Inc. and the ServiceTalk project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicetalk.examples.http.observer;

import io.servicetalk.http.api.BlockingHttpClient;
import io.servicetalk.http.api.HttpLifecycleObserver;
import io.servicetalk.http.netty.HttpClients;
import io.servicetalk.http.netty.HttpLifecycleObserverRequesterFilter;
import io.servicetalk.http.utils.HttpLifecycleObservers;

import static io.servicetalk.logging.api.LogLevel.TRACE;

/**
* An example multi-address client that shows {@link HttpLifecycleObserver} usage.
*/
public class LifecycleObserverUrlClient {
public static void main(String[] args) throws Exception {
// Note: this example demonstrates only blocking-aggregated programming paradigm, for asynchronous and
// streaming API see helloworld examples.
try (BlockingHttpClient client = HttpClients.forMultiAddressUrl().initializer((scheme, address, builder) -> {
// Append this filter first for most cases to maximize visibility!
// See javadocs on HttpLifecycleObserverRequesterFilter for more details on filter ordering.
// If necessary, users can set different filters based on `scheme` and/or `address`.
builder.appendClientFilter(new HttpLifecycleObserverRequesterFilter(
HttpLifecycleObservers.logging("servicetalk-examples-http-observer-logger", TRACE)));
}).buildBlocking()) {
client.request(client.get("http://localhost:8080/"));
// Ignore the response for this example. See logs for HttpLifecycleObserver results.
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright © 2023 Apple Inc. and the ServiceTalk project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicetalk.examples.http.retry;

import io.servicetalk.http.api.HttpClient;
import io.servicetalk.http.netty.HttpClients;
import io.servicetalk.http.netty.RetryingHttpRequesterFilter;

import static io.servicetalk.http.api.HttpResponseStatus.StatusClass.SERVER_ERROR_5XX;
import static io.servicetalk.http.api.HttpSerializers.textSerializerUtf8;

/**
* Extends the Async "Hello World" multi-address client to immediately retry requests that get a 5XX response. Up to
* three attempts total, one initial attempt and up to two retries, will be made before failure.
*/
public class RetryUrlClient {
public static void main(String[] args) throws Exception {
try (HttpClient client = HttpClients.forMultiAddressUrl().initializer((scheme, address, builder) -> {
// If necessary, users can set different retry strategies based on `scheme` and/or `address`.
builder.appendClientFilter(new RetryingHttpRequesterFilter.Builder()
.responseMapper(httpResponseMetaData ->
SERVER_ERROR_5XX.contains(httpResponseMetaData.status()) ?
// Response status is 500-599, we request a retry
new RetryingHttpRequesterFilter.HttpResponseException(
"Retry 5XX", httpResponseMetaData)
// Not a 5XX response, we do not know whether retry is required
: null)
.retryResponses((meta, error) -> RetryingHttpRequesterFilter.BackOffPolicy.ofImmediate(2))
.build());
}).build()) {
client.request(client.get("http://localhost:8080/sayHello"))
.whenOnSuccess(resp -> {
System.out.println(resp.toString((name, value) -> value));
System.out.println(resp.payloadBody(textSerializerUtf8()));
})
// This example is demonstrating asynchronous execution, but needs to prevent the main thread from exiting
// before the response has been processed. This isn't typical usage for an asynchronous API but is useful
// for demonstration purposes.
.toFuture().get();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright © 2023 Apple Inc. and the ServiceTalk project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicetalk.examples.http.timeout;

import io.servicetalk.concurrent.api.Single;
import io.servicetalk.http.api.HttpClient;
import io.servicetalk.http.api.HttpResponse;
import io.servicetalk.http.netty.HttpClients;
import io.servicetalk.http.utils.TimeoutHttpRequesterFilter;

import java.time.Duration;

import static io.servicetalk.concurrent.api.Single.collectUnorderedDelayError;
import static io.servicetalk.http.api.HttpSerializers.textSerializerUtf8;
import static java.time.Duration.ofSeconds;

/**
* Extends the async 'Hello World!' multi-address example to demonstrate use of timeout filters and timeout operators.
* If a single timeout can be applied to all transactions then the timeout should be applied using the
* {@link TimeoutHttpRequesterFilter}. If only some transactions require a timeout then the timeout should be applied
* using a {@link io.servicetalk.concurrent.api.Single#timeout(Duration)} Single.timeout()} or a
* {@link io.servicetalk.concurrent.api.Publisher#timeoutTerminal(Duration)} (Duration)} Publisher.timeoutTerminal()}
* operator.
*/
public class TimeoutUrlClient {
public static void main(String[] args) throws Exception {
try (HttpClient client = HttpClients.forMultiAddressUrl().initializer((scheme, address, builder) -> {
// Filter enforces that requests made with this client must fully complete
// within 10 seconds or will be cancelled.
// If necessary, users can set different timeout filters based on `scheme` and/or `address`.
builder.appendClientFilter(new TimeoutHttpRequesterFilter(ofSeconds(10), true));
}).build()) {
// first request, with default timeout from HttpClient (this will succeed)
Single<HttpResponse> respSingle1 = client.request(client.get("http://localhost:8080/defaultTimeout"))
.whenOnError(System.err::println)
.whenOnSuccess(resp -> {
System.out.println(resp.toString((name, value) -> value));
System.out.println(resp.payloadBody(textSerializerUtf8()));
});

// second request, with custom timeout that is lower than the client default (this will timeout)
Single<HttpResponse> respSingle2 = client.request(client.get("http://localhost:8080/3secondTimeout"))
// This request and response must complete within 3 seconds or the request will be cancelled.
.timeout(ofSeconds(3))
.whenOnError(System.err::println)
.whenOnSuccess(resp -> {
System.out.println(resp.toString((name, value) -> value));
System.out.println(resp.payloadBody(textSerializerUtf8()));
});

// Issue the requests in parallel.
collectUnorderedDelayError(respSingle1, respSingle2)
// This example is demonstrating asynchronous execution, but needs to prevent the main thread from exiting
// before the response has been processed. This isn't typical usage for an asynchronous API but is useful
// for demonstration purposes.
.toFuture().get();
}
}
}

0 comments on commit e123616

Please sign in to comment.