SpringBoot常用拦截器之ClientHttpRequestInterceptor
ClientHttpRequestInterceptor是Spring框架中用于拦截HTTP请求和响应的一个重要组件。它可以用于日志记录、权限校验、请求内容修改等场景。
以下是一个简单的ClientHttpRequestInterceptor实现示例,用于记录请求的详细信息:
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import java.io.IOException;
public class LoggingInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
long startTime = System.currentTimeMillis();
System.out.println("Start time: " + startTime + " URI: " + request.getURI());
ClientHttpResponse response = execution.execute(request, body);
long endTime = System.currentTimeMillis();
System.out.println("End time: " + endTime + " Duration: " + (endTime - startTime));
return response;
}
}
在Spring Boot应用中注册拦截器:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;
import java.util.Collections;
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestInterceptor loggingInterceptor) {
return new RestTemplate(Collections.singletonList(loggingInterceptor));
}
@Bean
public ClientHttpRequestInterceptor loggingInterceptor() {
return new LoggingInterceptor();
}
}
这个配置类创建了一个RestTemplate
实例,并注册了自定义的LoggingInterceptor
。这样,所有通过这个RestTemplate
发出的请求都会被LoggingInterceptor
拦截,并且会在控制台输出请求的开始时间、结束时间和耗时。
评论已关闭