Java Spring Boot-如何跟踪所有异常请求和响应并保存到数据库中?

Java Spring Boot-如何跟踪所有异常请求和响应并保存到数据库中?,java,spring,spring-boot,Java,Spring,Spring Boot,我有两个微服务(SpringBoot)用于两个产品之间的集成 产品1微服务1/微服务2产品1 我的任务是我需要使用输入PRAM(使用方法,如GET、POST等)跟踪请求,请求路径、查询字符串、该请求的对应类方法,以及该操作的响应、成功和错误,并保存到数据库表中。 我试过弹簧靴执行器。但是没有运气。 请建议如何实现这一目标 我建议使用HandlerInterceptor,您可以注册到两个micro services REST控制器。它有一个很好的生命周期回调,可以用来序列化数据并将其保存到数据库中

我有两个微服务(SpringBoot)用于两个产品之间的集成

产品1微服务1/微服务2产品1

我的任务是我需要使用输入PRAM(使用方法,如GET、POST等)跟踪请求,请求路径、查询字符串、该请求的对应类方法,以及该操作的响应、成功和错误,并保存到数据库表中。 我试过弹簧靴执行器。但是没有运气。
请建议如何实现这一目标

我建议使用
HandlerInterceptor
,您可以注册到两个micro services REST控制器。它有一个很好的生命周期回调,可以用来序列化数据并将其保存到数据库中。以下是自定义拦截器类:

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class DBRequestInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                         Object handler) throws Exception {

        // DB logic

        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                            Object handler, Exception ex) throws Exception {

        // DB logic

        super.afterCompletion(request, response, handler, ex);
    }
}
一旦开发了这个可重用的处理程序,就可以在web配置器中注册。代码如下:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

   @Autowired
   private DBRequestInterceptor interceptor;

   @Override
   public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(interceptor).addPathPatterns("/**/");
   }
}
这段代码在所有URL映射上注册拦截器。您可以将其自定义为某些特定的服务URL

一旦在上述拦截器中读取请求流,您可能会在原始代码中发现异常。在这种情况下,您可以利用Spring包装类
ContentCachingRequestWrapper


希望能有所帮助。

使用Zuul API捕获所有请求和响应我正在使用spring bootUse zipkin。你有github链接吗?这会很有用。如何保存有效负载?很遗憾,我没有上述代码的确切github链接。但是您可以使用
ContentCachingRequestWrapper
的InputStream方法读取正文。下面是
preHandle
方法httpservletrequestwrapper=newcontentcachingrequestwrapper(request)的示例代码;requestWrapper.getParameterMap();requestWrapper.getInputStream()//阅读流还有另一个拦截器,它可以直接获取正文内容,而无需使用包装器。下面是it的一个示例实现: