3

我正在尝试创建一个时间记录器过滤器来监视我的请求在使用 java 的框架 2 中占用的时间,但是过滤器的 java 端的文档很弱。

谁能指出我如何实现这一目标的正确方向?

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

4

1 回答 1

8

所以你会从这样的过滤器开始:

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  };
    }

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

于 2014-02-23T02:58:28.250 回答