-
Notifications
You must be signed in to change notification settings - Fork 180
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Demonstrate multi-address client in HTTP examples (#2709)
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
1 parent
9bc9746
commit e123616
Showing
7 changed files
with
264 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
78 changes: 78 additions & 0 deletions
78
...main/java/io/servicetalk/examples/http/compression/CompressionFilterExampleUrlClient.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
44 changes: 44 additions & 0 deletions
44
...erver/src/main/java/io/servicetalk/examples/http/observer/LifecycleObserverUrlClient.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | ||
} | ||
} | ||
} |
55 changes: 55 additions & 0 deletions
55
...-examples/http/retry/src/main/java/io/servicetalk/examples/http/retry/RetryUrlClient.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} | ||
} |
72 changes: 72 additions & 0 deletions
72
...les/http/timeout/src/main/java/io/servicetalk/examples/http/timeout/TimeoutUrlClient.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} | ||
} |