Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

F/delayed handler#100

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
billoneil merged 7 commits intomasterfromf/delayed-handler
Mar 14, 2019
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
packagecom.stubbornjava.common;

importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.Executors;
importjava.util.concurrent.TimeUnit;

importorg.jooq.lambda.Unchecked;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;

importcom.google.common.util.concurrent.MoreExecutors;

importokhttp3.OkHttpClient;
importokhttp3.Request;
importokhttp3.Response;

publicclassHttp {
privatestaticfinalLoggerlog =LoggerFactory.getLogger(Http.class);

// {{start:get}}
publicstaticResponseget(OkHttpClientclient,Stringurl) {
Requestrequest =newRequest.Builder()
.url(url)
.get()
.build();
returnUnchecked.supplier(() -> {
Responseresponse =client.newCall(request).execute();
returnresponse;
}).get();
}
// {{end:get}}

// {{start:getInParallel}}
publicstaticvoidgetInParallel(OkHttpClientclient,Stringurl,intcount) {
ExecutorServiceexec =Executors.newFixedThreadPool(count);
for (inti =0;i <count;i++) {
exec.submit(() ->Http.get(client,url));
}
MoreExecutors.shutdownAndAwaitTermination(exec,30,TimeUnit.SECONDS);
}
// {{end:getInParallel}}
}
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,7 +40,11 @@ private HttpClient() {
log.debug(msg);
});
static {
loggingInterceptor.setLevel(Level.BODY);
if (log.isDebugEnabled()) {
loggingInterceptor.setLevel(Level.BASIC);
}elseif (log.isTraceEnabled()) {
loggingInterceptor.setLevel(Level.BODY);
}
}

publicstaticHttpLoggingInterceptorgetLoggingInterceptor() {
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
packagecom.stubbornjava.common;


importjava.util.concurrent.TimeUnit;

importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;

importcom.google.common.base.Stopwatch;

publicclassTimers {
privatestaticfinalLoggerlogger =LoggerFactory.getLogger(Timers.class);

privateTimers() {}

publicstaticvoidtime(Stringmessage,Runnablerunnable) {
Stopwatchsw =Stopwatch.createStarted();
try {
logger.info("{}",message);
runnable.run();
}catch (Exceptionex) {
logger.warn("Exception in runnable",ex);
throwex;
}finally {
logger.info("{} took {}ms",message,sw.elapsed(TimeUnit.MILLISECONDS));
}
}

}
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,8 @@ public static SimpleServer simpleServer(HttpHandler handler) {
* If you base64 encode any cookie values you probably want it on.
*/
.setServerOption(UndertowOptions.ALLOW_EQUALS_IN_COOKIE_VALUE, true)
// Needed to set request time in access logs
.setServerOption(UndertowOptions.RECORD_REQUEST_START_TIME, true)
.addHttpListener(DEFAULT_PORT, DEFAULT_HOST, handler)
;
return new SimpleServer(undertow);
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
packagecom.stubbornjava.common.undertow;

importjava.net.InetSocketAddress;
importjava.util.function.Consumer;

importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;

importio.undertow.Undertow;
importio.undertow.Undertow.ListenerInfo;
importio.undertow.server.HttpHandler;

publicclassUndertowUtil {
privatestaticfinalLoggerlogger =LoggerFactory.getLogger(UndertowUtil.class);

/**
* This is currently intended to be used in unit tests but may
* be appropriate in other situations as well. It's not worth building
* out a test module at this time so it lives here.
*
* This helper will spin up the http handler on a random available port.
* The full host and port will be passed to the hostConsumer and the server
* will be shut down after the consumer completes.
*
* @param builder
* @param handler
* @param hostConusmer
*/
publicstaticvoiduseLocalServer(Undertow.Builderbuilder,
HttpHandlerhandler,
Consumer<String>hostConusmer) {
Undertowundertow =null;
try {
// Starts server on a random open port
undertow =builder.addHttpListener(0,"127.0.0.1",handler).build();
undertow.start();
ListenerInfolistenerInfo =undertow.getListenerInfo().get(0);
InetSocketAddressaddr = (InetSocketAddress)listenerInfo.getAddress();
Stringhost ="http://localhost:" +addr.getPort();
hostConusmer.accept(host);
}finally {
if (undertow !=null) {
undertow.stop();
}
}
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,7 +46,9 @@ public class CustomHandlers {
privatestaticfinalLoggerlog =LoggerFactory.getLogger(CustomHandlers.class);

publicstaticAccessLogHandleraccessLog(HttpHandlernext,Loggerlogger) {
returnnewAccessLogHandler(next,newSlf4jAccessLogReceiver(logger),"combined",CustomHandlers.class.getClassLoader());
// see http://undertow.io/javadoc/2.0.x/io/undertow/server/handlers/accesslog/AccessLogHandler.html
Stringformat ="%H %h %u\"%r\" %s %Dms %b bytes\"%{i,Referer}\"\"%{i,User-Agent}\"";
returnnewAccessLogHandler(next,newSlf4jAccessLogReceiver(logger),format,CustomHandlers.class.getClassLoader());
}

publicstaticAccessLogHandleraccessLog(HttpHandlernext) {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
packagecom.stubbornjava.common.undertow.handlers.diagnostic;

importjava.time.Duration;
importjava.util.concurrent.TimeUnit;
importjava.util.function.Function;

importio.undertow.server.Connectors;
importio.undertow.server.HttpHandler;
importio.undertow.server.HttpServerExchange;
importio.undertow.server.handlers.BlockingHandler;

// {{start:delayedHandler}}
/**
* A non blocking handler to add a time delay before the next handler
* is executed. If the exchange has already been dispatched this will
* un-dispatch the exchange and re-dispatch it before next is called.
*/
publicclassDelayedExecutionHandlerimplementsHttpHandler {

privatefinalHttpHandlernext;
privatefinalFunction<HttpServerExchange,Duration>durationFunc;

DelayedExecutionHandler(HttpHandlernext,
Function<HttpServerExchange,Duration>durationFunc) {
this.next =next;
this.durationFunc =durationFunc;
}

@Override
publicvoidhandleRequest(HttpServerExchangeexchange)throwsException {
Durationduration =durationFunc.apply(exchange);

finalHttpHandlerdelegate;
if (exchange.isBlocking()) {
// We want to undispatch here so that we are not blocking
// a worker thread. We will spin on the IO thread using the
// built in executeAfter.
exchange.unDispatch();
delegate =newBlockingHandler(next);
}else {
delegate =next;
}

exchange.dispatch(exchange.getIoThread(), () -> {
exchange.getIoThread().executeAfter(() ->
Connectors.executeRootHandler(delegate,exchange),
duration.toMillis(),
TimeUnit.MILLISECONDS);
});
}
}
// {{end:delayedHandler}}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
packagecom.stubbornjava.common.undertow.handlers.diagnostic;

importjava.time.Duration;
importjava.util.concurrent.ThreadLocalRandom;
importjava.util.concurrent.TimeUnit;

importio.undertow.server.HttpHandler;

publicclassDiagnosticHandlers {

// {{start:delayedHandler}}
/**
* Add a fixed delay before execution of the next handler
* @param next
* @param duration
* @param unit
* @return
*/
publicstaticDelayedExecutionHandlerfixedDelay(HttpHandlernext,
longduration,
TimeUnitunit) {
returnnewDelayedExecutionHandler(
next, (exchange) ->Duration.ofMillis(unit.toMillis(duration)));
}

/**
* Add a random delay between minDuration (inclusive) and
* maxDuration (exclusive) before execution of the next handler.
* This can be used to add artificial latency for requests.
*
* @param next
* @param minDuration inclusive
* @param maxDuration exclusive
* @param unit
* @return
*/
publicstaticDelayedExecutionHandlerrandomDelay(HttpHandlernext,
longminDuration,
longmaxDuration,
TimeUnitunit) {
returnnewDelayedExecutionHandler(
next, (exchange) -> {
longduration =ThreadLocalRandom.current()
.nextLong(minDuration,maxDuration);
returnDuration.ofMillis(unit.toMillis(duration));
});
}
// {{end:delayedHandler}}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
packagecom.stubbornjava.common.undertow.handlers.diagnostic;

importstaticorg.junit.Assert.assertTrue;

importjava.util.List;
importjava.util.concurrent.Callable;
importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.Executors;
importjava.util.concurrent.Future;
importjava.util.concurrent.TimeUnit;
importjava.util.stream.Collectors;
importjava.util.stream.IntStream;

importorg.jooq.lambda.Seq;
importorg.jooq.lambda.Unchecked;
importorg.junit.Assert;
importorg.junit.Test;

importcom.google.common.base.Stopwatch;
importcom.google.common.util.concurrent.MoreExecutors;
importcom.stubbornjava.common.Http;
importcom.stubbornjava.common.HttpClient;
importcom.stubbornjava.common.undertow.Exchange;
importcom.stubbornjava.common.undertow.UndertowUtil;
importcom.stubbornjava.common.undertow.handlers.CustomHandlers;
importcom.stubbornjava.undertow.handlers.MiddlewareBuilder;

importio.undertow.Undertow;
importio.undertow.server.HttpHandler;
importio.undertow.server.handlers.BlockingHandler;
importokhttp3.OkHttpClient;
importokhttp3.Response;

publicclassDelayedExecutionHandlerTest {

// Delay for 500ms then return "ok"
privatestaticfinalDelayedExecutionHandlerdelayedHandler =
DiagnosticHandlers.fixedDelay((exchange) -> {
Exchange.body().sendText(exchange,"ok");
},
500,TimeUnit.MILLISECONDS);

@Test
publicvoidtestOnXIoThread()throwsInterruptedException {
intnumThreads =10;
run(delayedHandler,numThreads);
}

@Test
publicvoidtestOnWorkerThread()throwsInterruptedException {
intnumThreads =10;
run(newBlockingHandler(delayedHandler),numThreads);
}

/**
* Spin up a new server with a single IO thread and worker thread.
* Run N GET requests against it concurrently and make sure they
* do not take N * 500ms total. This is not the best test but it
* should show that we are delaying N requests at once using a single
* thread.
*
* @param handler
* @param numThreads
* @throws InterruptedException
*/
privatevoidrun(HttpHandlerhandler,intnumThreads)throwsInterruptedException {
HttpHandlerroute =MiddlewareBuilder.begin(CustomHandlers::accessLog)
.complete(handler);
Undertow.Builderbuilder =Undertow.builder()
.setWorkerThreads(1)
.setIoThreads(1);
UndertowUtil.useLocalServer(builder,route,host -> {
ExecutorServiceexec =Executors.newFixedThreadPool(numThreads);
OkHttpClientclient =newOkHttpClient().newBuilder()
.addInterceptor(HttpClient.getLoggingInterceptor())
.build();

// Using time in tests isn't the best approach but this one seems
// A little difficult to test another way.
Stopwatchsw =Stopwatch.createStarted();
List<Callable<Response>>callables =IntStream.range(0,numThreads)
.mapToObj(i -> (Callable<Response>) () ->Http.get(client,host))
.collect(Collectors.toList());
sw.stop();
Seq.seq(Unchecked.supplier(() ->exec.invokeAll(callables)).get())
.map(Unchecked.function(Future::get))
.forEach(DelayedExecutionHandlerTest::assertSuccess);
assertTrue("Responses took too long",sw.elapsed().toMillis() <1_000);
MoreExecutors.shutdownAndAwaitTermination(exec,10,TimeUnit.SECONDS);
});
}

privatestaticvoidassertSuccess(Responseresponse) {
Assert.assertTrue("Response should be a 200",response.isSuccessful());
}

}
Loading

[8]ページ先頭

©2009-2025 Movatter.jp