gpt4 book ai didi

java - EssentialFilter play framework java(记录时间)

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:11:28 25 4
gpt4 key购买 nike

我正在尝试创建一个时间记录器过滤器来监控我的请求使用 java 进入 play framework 2 的时间,但是过滤器的 java 端的文档很薄弱。

任何人都可以为我指出正确的方向来实现这一目标吗?

scala 指南位于 http://www.playframework.com/documentation/2.1.3/ScalaHttpFilters

最佳答案

所以你会像这样开始使用过滤器:

public class TimeLoggingFilter implements EssentialFilter {

public EssentialAction apply(final EssentialAction next) {

return new TimeLoggingAction() {

@Override
public EssentialAction apply() {
return next.apply();
}

@Override
public Iteratee<byte[], SimpleResult> apply(final RequestHeader rh) {
final long startTime = System.currentTimeMillis();

return next.apply(rh).map(new AbstractFunction1<SimpleResult, SimpleResult>() {

@Override
public SimpleResult apply(SimpleResult v1) {
long time = logTime(rh, startTime);
List<Tuple2<String, String>> list = new ArrayList<Tuple2<String, String>>();
Tuple2<String, String> t =
new Tuple2<String, String>("Request-Time",
String.valueOf(time));
list.add(t);
Seq<Tuple2<String, String>> seq = Scala.toSeq(list);
return v1.withHeaders(seq);
}

@Override
public <A> Function1<SimpleResult, A> andThen(Function1<SimpleResult, A> g) {
return g;
}

@Override
public <A> Function1<A, SimpleResult> compose(Function1<A, SimpleResult> g) {
return g;
}

}, Execution.defaultExecutionContext());
}


private long logTime(RequestHeader request, long startTime) {
long endTime = System.currentTimeMillis();
long requestTime = endTime - startTime;
Logger.info(request.uri() + " from " + request.remoteAddress() + " took " + requestTime + " ms");

return requestTime;
}
};
}

public abstract class TimeLoggingAction extends
AbstractFunction1<RequestHeader, Iteratee<byte[], SimpleResult>>
implements EssentialAction {}
}

然后将其连接到您的 Global.java 中:

public <T extends EssentialFilter> Class<T>[] filters() {
return new Class[] { TimeLoggingFilter.class };
}

我今天自己也在寻找一个类似的例子,但没有找到任何东西 - 但这似乎有效。

关于java - EssentialFilter play framework java(记录时间),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19316080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com