我不知道有没有办法获取定时器上下文对象,但我有另一个想法。你说这个方法不常被调用。为什么不使用 DynamicFeature 并打印容器的执行时间?
下面我将向您展示如何实现这一点。我不确定这是否有效,我只是在没有任何测试的情况下对其进行了编码,因此请尝试并在需要时进行更改。如果 ExecutionTimeFilter 由于实现了接口而需要拆分为两个单独的类,则相应地进行更改。
第 1 步:创建过滤器
@Provider
public class ExecutionTimeFilter implements ContainerRequestFilter, ContainerResponseFilter {
public static final String EXECUTION_TIME_HEADER = "X-Execution-Time";
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
requestContext.getHeaders().add(EXECUTION_TIME_HEADER, ZonedDateTime.now().toString());
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
ZonedDateTime executionStartHeader = ZonedDateTime.parse(requestContext.getHeaderString(EXECUTION_TIME_HEADER));
Duration executionTime = Duration.between(executionStartHeader, ZonedDateTime.now());
//you can also print some url informations or whatever you need; check out the informations from both mehtod params
System.out.println("The execution time was:" + executionTime);
}
}
第 2 步:创建动态特征
@Provider
public class ExecutionTimeFeature implements DynamicFeature {
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
if (resourceInfo.getResourceMethod().getAnnotation(ExecutionTime.class) != null) {
context.register(ExecutionTimeFilter.class);
}
}
}
第 3 步:创建注释
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExecutionTime {
}
第 4 步:注释您的资源
@GET
@ExecutionTime
public String getExcpensiveCalculation(@QueryParam("number") @DefaultValue("1") IntegerParam number) {
return getCalculation(number);
}
第 5 步:注册功能
environment.jersey().register(ExecutionTimeFeature.class);
参考资料:Dropwizard Dynamic Feature with Filters