记录OpenFeign一个好玩的事儿

83 阅读1分钟

发现个好玩的事儿

图片

我先定义一个FeignClient

@FeignClient(name = "DemoClient", url = "${" + DemoProperties.BASE_URI_CONFIG_KEY + "}")
public interface DemoClient {
}

我再定义一个拦截器

@Slf4j
@Component
public class DemoRequestInterceptor implements RequestInterceptor {

  @Autowired
  private DemoProperties demoProperties;

  @Override
  public void apply(RequestTemplate template) {
    if (DemoClient.class.isAssignableFrom(template.feignTarget().type())) {
      template.target(demoProperties.getBaseUri());
      template.header(DemoProperties.API_KEY_NAME, demoProperties.getApiKey());
      template.header(DemoProperties.APP_KEY_NAME, demoProperties.getAppKey());
    }
  }
}

如果feignClient中的url不是http打头,在发起调用的时候feign还是会走到服务发现去找对应服务提供者信息,尽管我在拦截器中通过template.target修改了目标信息

反之如果feignClient中的url是http打头,在发起调用的时候feign不会走服务发现,并且在拦截中通过通过template.target方法修改目标信息可以生效

本文使用 文章同步助手 同步