首页 > 解决方案 > 在 Spring 中如何审计端点通信?

问题描述

我的意图是通过我的应用程序的端点审核数据交换。我想检索通过端点交换的 json 并将其存储在数据库中。为了存储 json 数据,我将使用 Javes ( https://javers.org/ ),但我仍然需要弄清楚如何获取端点数据。

标签: javaspringspring-bootspring-mvcauditing

解决方案


您可以编写拦截器来对流经您的应用程序的请求和响应进行额外处理。如果你正在使用spring它很容易实现。这是一个例子:

@Component
public class RestInterceptor implements ClientHttpRequestInterceptor {

 @Override
 public ClientHttpResponse intercept(HttpRequest request, byte[] body,
  ClientHttpRequestExecution execution) throws IOException {
  traceRequest(request, body);
  ClientHttpResponse response = execution.execute(request, body);
  traceResponse(response);
  return response;
 }

 private void traceRequest(HttpRequest request, byte[] body) throws IOException {
   //track request here
 }


 private void traceResponse(ClientHttpResponse response) throws IOException {
    //track response here
 }

}

现在用你的休息模板注册它

restTemplate.setInterceptors(Collections.singletonList(new RestInterceptor ()));

推荐阅读