Ribbon拦截器添加请求头

定义拦截器

@Slf4j
@Component
public class MyRibbonInterceptor implements ClientHttpRequestInterceptor {


    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution execution) throws IOException {
        log.info("host,path:{},{}",httpRequest.getURI().getHost(),httpRequest.getURI().getPath());
        httpRequest.getHeaders().set("aaa","bbb");
        return execution.execute(httpRequest,bytes);
    }
}

 

@Configuration
public class WebConfig {

    @Autowired
    private MyRibbonInterceptor myRibbonInterceptor;

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(Collections.singletonList(myRibbonInterceptor));
        return restTemplate;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring中,常用的拦截器有以下几种: 1. HandlerInterceptor:最常见的拦截器,用于拦截来自客户端浏览器等的HTTP请求。 2. ClientHttpRequestInterceptor:用于拦截RestTemplate的请求,也被称为RestTemplate拦截器Ribbon拦截器。 3. RequestInterceptor:常用于Feign调用,也是一个HTTP拦截器。 下面是HandlerInterceptor的使用方法: 1. 创建一个类并实现HandlerInterceptor接口。 2. 在类上使用@Component注解,将其声明为Spring Bean。 3. 在类上使用@Order注解指定拦截器的执行顺序。 4. 实现HandlerInterceptor接口的三个方法:preHandle、postHandle和afterCompletion。 5. 在配置类中使用addInterceptor方法将拦截器添加拦截器链中。 下面是一个HandlerInterceptor的示例代码: ```java @Component @Order(1) public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 在请求处理之前进行调用(Controller方法调用之前) return true; // 如果返回false,则请求中断 } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后) } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // 在整个请求结束之后被调用,也就是在DispatcherServlet渲染了对应的视图之后执行(主要是用于进行资源清理工作) } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值