我有一些重复的代码:
router.post("/fleets/:fleetid/vehicles/:boxid/ping").handler(ctx -> pingBox(pingBoxTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/wakeup").handler(ctx -> wakeUp(wakeupTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/passthrough").handler(ctx -> passthrough(passthroughTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/expert").handler(ctx -> passthrough(passthroughTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/door").handler(ctx -> door(doorTimer, oemUrl, ctx));
在这些方法的处理程序中,我:
例如:
private void pingBox(Timer timer, String someArgs, RoutingContext ctx) {
log.debug("ping request");
Timer.Context timerCtx = timer.time();
ctx.put("timer", timerCtx);
ctx.response().headers().add("content-type", "text/plain");
ctx.response().end("pong");
timerCtx.stop();
}
如何包装处理程序以避免重复代码?
我尝试了以下方法:
private void handleWithTimer(Timer timer, String url, RoutingContext ctx, BiConsumer<String, RoutingContext> handler){
log.debug("saving timer");
Timer.Context timerCtx = timer.time();
ctx.put("timer", timerCtx);
handler.accept(url, ctx);
timerCtx.stop();
}
但结果不可读。
.. .handler(ctx -> handleWithTimer(pingBoxTimer, oemUrl, ctx, (s, c) -> pingBox(oemUrl, ctx)));
必须有一种更简洁的方法。有什么想法吗?
谢谢
答案 0 :(得分:4)
您可以像这样使包装函数更具可读性:
.handler(ctx -> handleWithTimer(pingBoxTimer, oemUrl, ctx, this::pingBox));
(当然,只有在调整了pingBox的输入参数后,看来您已经这样做了)