use of io.servicetalk.transport.api.IoExecutor in project servicetalk by apple.
the class BackendsStarter method main.
public static void main(String[] args) throws Exception {
// Create an AutoCloseable representing all resources used in this example.
try (CompositeCloseable resources = newCompositeCloseable()) {
// Shared IoExecutor for the application.
IoExecutor ioExecutor = resources.prepend(createIoExecutor());
// This is a single Completable used to await closing of all backends started by this class. It is used to
// provide a way to not let main() exit.
Completable allServicesOnClose = completed();
BackendStarter starter = new BackendStarter(ioExecutor, resources);
final ServerContext recommendationService = starter.start(RECOMMENDATIONS_BACKEND_ADDRESS.port(), RECOMMENDATION_SERVICE_NAME, newRecommendationsService());
allServicesOnClose = allServicesOnClose.merge(recommendationService.onClose());
final ServerContext metadataService = starter.start(METADATA_BACKEND_ADDRESS.port(), METADATA_SERVICE_NAME, newMetadataService());
allServicesOnClose = allServicesOnClose.merge(metadataService.onClose());
final ServerContext userService = starter.start(USER_BACKEND_ADDRESS.port(), USER_SERVICE_NAME, newUserService());
allServicesOnClose = allServicesOnClose.merge(userService.onClose());
final ServerContext ratingService = starter.start(RATINGS_BACKEND_ADDRESS.port(), RATING_SERVICE_NAME, newRatingService());
allServicesOnClose = allServicesOnClose.merge(ratingService.onClose());
// Await termination of all backends started by this class.
allServicesOnClose.toFuture().get();
}
}
use of io.servicetalk.transport.api.IoExecutor in project servicetalk by apple.
the class DefaultMultiAddressUrlHttpClientBuilderTest method internalClientsUseDifferentExecutionContextWhenConfigured.
@Test
void internalClientsUseDifferentExecutionContextWhenConfigured() throws Exception {
// Assert prerequisites first.
// Use different strategies, as ExecutionContextExtension shares the same strategy.
HttpExecutionStrategy internalExecutionStrategy = HttpExecutionStrategies.customStrategyBuilder().offloadNone().build();
HttpExecutionStrategy externalExecutionStrategy = HttpExecutionStrategies.customStrategyBuilder().offloadAll().build();
assertThat(internalExecutionStrategy, not(equalTo(externalExecutionStrategy)));
BufferAllocator internalBufferAllocator = BufferAllocators.PREFER_DIRECT_ALLOCATOR;
BufferAllocator externalBufferAllocator = BufferAllocators.PREFER_HEAP_ALLOCATOR;
assertThat(internalBufferAllocator, not(equalTo(externalBufferAllocator)));
assertThat(CTX.executor(), not(equalTo(INTERNAL_CLIENT_CTX.executor())));
assertThat(CTX.ioExecutor(), not(equalTo(INTERNAL_CLIENT_CTX.ioExecutor())));
try (ServerContext serverContext = HttpServers.forAddress(localAddress(0)).executionStrategy(offloadNever()).listenStreamingAndAwait((ctx, request, responseFactory) -> succeeded(responseFactory.ok()))) {
AtomicReference<BufferAllocator> actualInternalBufferAllocator = new AtomicReference<>();
AtomicReference<IoExecutor> actualInternalIoExecutor = new AtomicReference<>();
AtomicReference<Executor> actualInternalExecutor = new AtomicReference<>();
AtomicReference<ExecutionStrategy> actualInternalExecutionStrategy = new AtomicReference<>();
final StreamingHttpClient streamingHttpClient = HttpClients.forMultiAddressUrl().initializer((scheme, address, builder) -> builder.executionStrategy(internalExecutionStrategy).executor(INTERNAL_CLIENT_CTX.executor()).ioExecutor(INTERNAL_CLIENT_CTX.ioExecutor()).bufferAllocator(internalBufferAllocator).executionStrategy(internalExecutionStrategy).appendClientFilter(client -> {
HttpExecutionContext internalContext = client.executionContext();
actualInternalBufferAllocator.set(internalContext.bufferAllocator());
actualInternalExecutor.set(internalContext.executor());
actualInternalIoExecutor.set(internalContext.ioExecutor());
actualInternalExecutionStrategy.set(internalContext.executionStrategy());
return new StreamingHttpClientFilter(client) {
};
})).executor(CTX.executor()).ioExecutor(CTX.ioExecutor()).executionStrategy(externalExecutionStrategy).bufferAllocator(externalBufferAllocator).buildStreaming();
assertNotNull(streamingHttpClient);
// Check external client
final HttpExecutionContext executionContext = streamingHttpClient.executionContext();
assertThat(executionContext.executor(), equalTo(CTX.executor()));
assertThat(executionContext.executionStrategy(), equalTo(externalExecutionStrategy));
assertThat(executionContext.ioExecutor(), equalTo(CTX.ioExecutor()));
assertThat(executionContext.bufferAllocator(), equalTo(CTX.bufferAllocator()));
// Make a request to trigger the filter execution that extracts the execution context.
final HostAndPort address = HostAndPort.of((InetSocketAddress) serverContext.listenAddress());
streamingHttpClient.reserveConnection(streamingHttpClient.get("http://" + address)).toFuture().get();
// Check internal client
assertThat(actualInternalBufferAllocator.get(), equalTo(internalBufferAllocator));
assertThat(actualInternalExecutor.get(), equalTo(INTERNAL_CLIENT_CTX.executor()));
assertThat(actualInternalIoExecutor.get(), equalTo(INTERNAL_CLIENT_CTX.ioExecutor()));
assertThat(actualInternalExecutionStrategy.get(), equalTo(internalExecutionStrategy));
streamingHttpClient.closeAsync().toFuture().get();
}
}
use of io.servicetalk.transport.api.IoExecutor in project servicetalk by apple.
the class GrpcUdsTest method udsRoundTrip.
@Test
void udsRoundTrip() throws Exception {
Assumptions.assumeTrue(ioExecutor.isUnixDomainSocketSupported());
String greetingPrefix = "Hello ";
String name = "foo";
String expectedResponse = greetingPrefix + name;
try (ServerContext serverContext = forAddress(newSocketAddress()).initializeHttp(builder -> builder.ioExecutor(ioExecutor)).listenAndAwait((GreeterService) (ctx, request) -> succeeded(HelloReply.newBuilder().setMessage(greetingPrefix + request.getName()).build()));
BlockingGreeterClient client = forResolvedAddress(serverContext.listenAddress()).buildBlocking(new ClientFactory())) {
assertEquals(expectedResponse, client.sayHello(HelloRequest.newBuilder().setName(name).build()).getMessage());
}
}
use of io.servicetalk.transport.api.IoExecutor in project servicetalk by apple.
the class GatewayServer method main.
/**
* Starts this server.
*
* @param args Program arguments, none supported yet.
* @throws Exception If the server could not be started.
*/
public static void main(String[] args) throws Exception {
// Create an AutoCloseable representing all resources used in this example.
try (CompositeCloseable resources = newCompositeCloseable()) {
// Shared IoExecutor for the application.
IoExecutor ioExecutor = resources.prepend(createIoExecutor());
// Create clients for the different backends we are going to use in the gateway.
StreamingHttpClient recommendationsClient = newClient(ioExecutor, RECOMMENDATIONS_BACKEND_ADDRESS, resources, "recommendations backend");
HttpClient metadataClient = newClient(ioExecutor, METADATA_BACKEND_ADDRESS, resources, "metadata backend").asClient();
HttpClient userClient = newClient(ioExecutor, USER_BACKEND_ADDRESS, resources, "user backend").asClient();
HttpClient ratingsClient = newClient(ioExecutor, RATINGS_BACKEND_ADDRESS, resources, "ratings backend").asClient();
// Gateway supports different endpoints for blocking, streaming or aggregated implementations.
// We create a router to express these endpoints.
HttpPredicateRouterBuilder routerBuilder = new HttpPredicateRouterBuilder();
final StreamingHttpService gatewayService = routerBuilder.whenPathStartsWith("/recommendations/stream").thenRouteTo(new StreamingGatewayService(recommendationsClient, metadataClient, ratingsClient, userClient)).whenPathStartsWith("/recommendations/aggregated").thenRouteTo(new GatewayService(recommendationsClient.asClient(), metadataClient, ratingsClient, userClient)).whenPathStartsWith("/recommendations/blocking").thenRouteTo(new BlockingGatewayService(recommendationsClient.asBlockingClient(), metadataClient.asBlockingClient(), ratingsClient.asBlockingClient(), userClient.asBlockingClient())).buildStreaming();
// Create configurable starter for HTTP server.
// Starting the server will start listening for incoming client requests.
ServerContext serverContext = HttpServers.forPort(8080).ioExecutor(ioExecutor).appendServiceFilter(new BadResponseHandlingServiceFilter()).listenStreamingAndAwait(gatewayService);
LOGGER.info("Listening on {}", serverContext.listenAddress());
// Blocks and awaits shutdown of the server this ServerContext represents.
serverContext.awaitShutdown();
}
}
use of io.servicetalk.transport.api.IoExecutor in project FrameworkBenchmarks by TechEmpower.
the class Server method main.
public static void main(String[] args) throws Exception {
/*
* Disable AsyncContext
*/
AsyncContext.disable();
/*
* Factory to implement io pooling
*/
IoExecutor ioExecutor = NettyIoExecutors.createIoExecutor(Runtime.getRuntime().availableProcessors(), new IoThreadFactory("io-pool"));
/*
* Factory to disable headers validation
*/
DefaultHttpHeadersFactory headersFactory = new DefaultHttpHeadersFactory(false, false);
HttpSerializationProvider serializer = HttpSerializationProviders.jsonSerializer(new JacksonSerializationProvider());
// Create a custom server builder with performance enhancements
HttpServers.forPort(8080).executionStrategy(HttpExecutionStrategies.noOffloadsStrategy()).ioExecutor(ioExecutor).disableDrainingRequestPayloadBody().protocols(HttpProtocolConfigs.h1().headersFactory(headersFactory).build()).appendConnectionAcceptorFilter(delegate -> new ConnectionAcceptor() {
@Override
public Completable accept(ConnectionContext context) {
((NettyConnectionContext) context).updateFlushStrategy((current, isOrig) -> FlushStrategies.flushOnEnd());
return delegate.accept(context);
}
}).listenAndAwait((ctx, request, responseFactory) -> {
((NettyConnectionContext) ctx).updateFlushStrategy(((current, isCurrentOriginal) -> FlushStrategies.flushOnEach()));
if (request.path().equals("/json")) {
Map<String, String> obj = new HashMap<String, String>();
obj.put("message", "Hello, World!");
return succeeded(responseFactory.ok().payloadBody(obj, serializer.serializerFor(Map.class)).addHeader("Date", getCurrentTime()).addHeader("Server", "ServiceTalk"));
}
if (request.path().equals("/plaintext")) {
return succeeded(responseFactory.ok().payloadBody("Hello, World!", HttpSerializationProviders.textSerializer()).addHeader("Date", getCurrentTime()).addHeader("Server", "ServiceTalk"));
}
;
return null;
}).awaitShutdown();
}
Aggregations