Spring 5 WebFlux中的拦截器 [英] Interceptor in Spring 5 WebFlux

查看:2125
本文介绍了Spring 5 WebFlux中的拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用Spring WebFlux.我想创建一个拦截器来计算每个API花费的时间.在Spring MVC中,我们有HandlerInterceptor,而在spring-boot-starter-webflux中不存在.我尝试添加spring-boot-starter-web并编写了拦截器,但没有成功.这是代码:

I am using Spring WebFlux in my project. I want to create an interceptor to calculate the time taken by each API. In Spring MVC we have HandlerInterceptor which is not present in spring-boot-starter-webflux. I tried adding spring-boot-starter-web and wrote my interceptor but it didn't work. Here is the code:

@Component
public class TimeInterceptor implements HandlerInterceptor {

public static Logger logger = Logger.getLogger(TimeInterceptor.class);

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    long startTime = System.currentTimeMillis();
    request.setAttribute("startTime", startTime);
    return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    long totaltime = System.currentTimeMillis() - (long) request.getAttribute("startTime");
    request.setAttribute("totaltime", totaltime);
    logger.info("Logging total time" + totaltime);

}
...
...

我想向我的应用程序添加类似的功能,并拦截每次调用所花费的时间.

I want to add similar functionality to my application and intercept time taken by each call.

谢谢.

推荐答案

Spring WebFlux中没有HandlerInterceptor的概念,但是您可以使用自己的WebFilter来代替.

There is no concept of HandlerInterceptor in Spring WebFlux, but you can use your own WebFilter for that instead.

您要描述的功能听起来很像执行器和千分尺提供的指标支持.如果您想尝试:

The feature you're describing sounds a lot like the metrics support provided by Actuator and Micrometer. If you'd like to try it:

  1. 将执行器依赖项添加到您的项目中
  2. 公开并选择服务器HTTP请求的度量标准(请参阅
  1. Add the actuator dependency to your project
  2. Expose the relevant endpoints (here, metrics)
  3. Go to "/actuator/metrics and select the metric for server HTTP requests (see the reference documentation).

千分尺提供了更多方法,并可以帮助您正确设置指标,例如:在测量时间时考虑GC暂停,提供直方图/百分位数/...等.

Micrometer offers way more and helps you to get your metrics right, like: taking into account GC pauses when measuring time, providing histograms/percentiles/..., and more.

注意:将spring-boot-starter-web添加到您的应用程序会将其变成Spring MVC应用程序.

Note: adding spring-boot-starter-web to your application will turn it into a Spring MVC application.

这篇关于Spring 5 WebFlux中的拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆