feign 全局传递请求头参数

参考文档:https://blog.csdn.net/lidai352710967/article/details/88680173

1、feign拦截器

@Configuration
public class FeignConfiguration implements RequestInterceptor {

@Override
public void apply(RequestTemplate requestTemplate) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    requestTemplate.header("Token", request.getHeader("Token"));
}

上述方式只对semophone策略有效,需要如下配置

hystrix:
  command:
    default:
      execution:
        isolation:
          strategy: SEMAPHORE

2、自定义熔断策略,配合RequestInterceptor 使用


import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariable;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle;
import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier;
import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: luosai
 * @Date: 2019/9/4 17:37
 */
@Slf4j
@Configuration
public class FeignHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
  private HystrixConcurrencyStrategy delegate;

  public FeignHystrixConcurrencyStrategy() {
    try {
      this.delegate = HystrixPlugins.getInstance().getConcurrencyStrategy();
      if (this.delegate instanceof FeignHystrixConcurrencyStrategy) {
        // Welcome to singleton hell...
        return;
      }
      HystrixCommandExecutionHook commandExecutionHook =
              HystrixPlugins.getInstance().getCommandExecutionHook();
      HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance().getEventNotifier();
      HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher();
      HystrixPropertiesStrategy propertiesStrategy =
              HystrixPlugins.getInstance().getPropertiesStrategy();
      this.logCurrentStateOfHystrixPlugins(eventNotifier, metricsPublisher, propertiesStrategy);
      HystrixPlugins.reset();
      HystrixPlugins.getInstance().registerConcurrencyStrategy(this);
      HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook);
      HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);
      HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher);
      HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);
    } catch (Exception e) {
      log.error("Failed to register Sleuth Hystrix Concurrency Strategy", e);
    }
  }

  private void logCurrentStateOfHystrixPlugins(HystrixEventNotifier eventNotifier,
                                               HystrixMetricsPublisher metricsPublisher, HystrixPropertiesStrategy propertiesStrategy) {
    if (log.isDebugEnabled()) {
      log.debug("Current Hystrix plugins configuration is [" + "concurrencyStrategy ["
              + this.delegate + "]," + "eventNotifier [" + eventNotifier + "]," + "metricPublisher ["
              + metricsPublisher + "]," + "propertiesStrategy [" + propertiesStrategy + "]," + "]");
      log.debug("Registering Sleuth Hystrix Concurrency Strategy.");
    }
  }

  @Override
  public <T> Callable<T> wrapCallable(Callable<T> callable) {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    return new WrappedCallable<>(callable, requestAttributes);
  }

  @Override
  public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
                                          HystrixProperty<Integer> corePoolSize, HystrixProperty<Integer> maximumPoolSize,
                                          HystrixProperty<Integer> keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
    return this.delegate.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize, keepAliveTime,
            unit, workQueue);
  }

  @Override
  public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
                                          HystrixThreadPoolProperties threadPoolProperties) {
    return this.delegate.getThreadPool(threadPoolKey, threadPoolProperties);
  }

  @Override
  public BlockingQueue<Runnable> getBlockingQueue(int maxQueueSize) {
    return this.delegate.getBlockingQueue(maxQueueSize);
  }

  @Override
  public <T> HystrixRequestVariable<T> getRequestVariable(HystrixRequestVariableLifecycle<T> rv) {
    return this.delegate.getRequestVariable(rv);
  }

  static class WrappedCallable<T> implements Callable<T> {
    private final Callable<T> target;
    private final RequestAttributes requestAttributes;

    public WrappedCallable(Callable<T> target, RequestAttributes requestAttributes) {
      this.target = target;
      this.requestAttributes = requestAttributes;
    }

    @Override
    public T call() throws Exception {
      try {
        RequestContextHolder.setRequestAttributes(requestAttributes);
        return target.call();
      } finally {
        RequestContextHolder.resetRequestAttributes();
      }
    }
  }


}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用Feign发送POST请求时,可以通过多种方式传递参数,包括请求体、表单参数、路径参数请求等。下面是一些常见的示例: 1. 传递请求参数:可以使用`@RequestBody`注解将参数对象作为请求体发送。示例代码如下: ```java @RequestMapping(method = RequestMethod.POST, value = "/api/endpoint") ResponseEntity<String> postWithRequestBody(@RequestBody RequestData requestData); ``` 2. 传递表单参数:可以使用`@RequestParam`注解将参数作为表单参数发送。示例代码如下: ```java @RequestMapping(method = RequestMethod.POST, value = "/api/endpoint") ResponseEntity<String> postWithFormParams(@RequestParam("param1") String param1, @RequestParam("param2") String param2); ``` 3. 传递路径参数:可以使用`@PathVariable`注解将参数作为路径参数发送。示例代码如下: ```java @RequestMapping(method = RequestMethod.POST, value = "/api/endpoint/{id}") ResponseEntity<String> postWithPathParam(@PathVariable("id") String id); ``` 4. 传递请求:可以使用`@RequestHeader`注解将参数作为请求发送。示例代码如下: ```java @RequestMapping(method = RequestMethod.POST, value = "/api/endpoint") ResponseEntity<String> postWithRequestHeader(@RequestHeader("Authorization") String authorization); ``` 对于返回值,Feign默认使用Spring的`ResponseEntity`作为返回类型。可以根据实际情况设置合适的泛型类型,以便正确处理返回值。示例代码如下: ```java @RequestMapping(method = RequestMethod.POST, value = "/api/endpoint") ResponseEntity<MyResponse> postAndGetResponse(); ``` 在上述示例中,`MyResponse`是自定义的响应对象类型。 以上是一些常见的参数传递和返回值处理的示例,具体的使用方式可以根据实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值