【问题标题】:Programmatically retrieve URL called by Spring FeignClient以编程方式检索 Spring FeignClient 调用的 URL
【发布时间】:2019-11-12 16:15:23
【问题描述】:

我正在尝试找到一种方法来检索当前由 Spring 应用程序中的 Feign Client 方法接口映射的 URL,但我还没有找到解决方案。以下代码有效:

pom.xml

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-openfeign</artifactId>
  <version>2.1.1.RELEASE</version>
</dependency>

application.yml

api:
  url: https://jsonplaceholder.typicode.com

ApiClient.class

package com.example.feign;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name = "json-placeholder", url = "${api.url}")
public interface ApiClient {

    @GetMapping(value = "/posts", consumes = "application/json")
    ResponseEntity<String> getPosts();
}

FeignApplication.class

package com.example.feign;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

import javax.annotation.PostConstruct;

@EnableFeignClients
@SpringBootApplication
public class FeignApplication {

    public static void main(String[] args) {
        SpringApplication.run(FeignApplication.class, args);
    }

    @Autowired
    private ApiClient apiClient;

    @PostConstruct
    public void test() {

        // this works
        System.out.println(apiClient.getPosts().getBody());

        // apiClient. ... getPosts request URL
    }
}

我尝试编写直接从注释读取的 URL,但它似乎不起作用。谁能给我一个替代方案?谢谢。

  • 编辑笔记 -

抱歉,由于在应用提供的解决方案时出现意外问题,我对我的问题做了一些小改动。

如果注释属性中设置的值是文字,则直接从注释中读取有效。如果从 application.yml 文件中读取该值,则注解属性返回的 URL 是表达式 ifself,而不是解析后的值。

关于这个更新的场景有什么想法吗?我需要的是 FeignClient 实际调用的 URL。我知道所有提供的解决方案实际上都是解决方法。

【问题讨论】:

  • 为了更清楚,指定的行应该打印"https://jsonplaceholder.typicode.com/posts"
  • 一个简单的解决方法是将 URL 设置为 ApiClient 的公共静态最终字符串字段,例如public static final String URL = "https://jsonplaceholder.typicode.com"。您的注解可以使用url = ApiClient.URL 引用它。然后你可以在任何地方引用这个变量。
  • 对不起,我可以这样做。请看我更新的声明。 URL 值需要作为 application.yml 属性注入,并且会因环境而异。

标签: java spring spring-boot spring-cloud-feign


【解决方案1】:

我不确定你是否还在寻找答案,但我的方法如下

  1. 返回响应
import feign.Response;

@FeignClient(name = "json-placeholder", url = "${api.url}")
public interface ApiClient {

    @GetMapping(value = "/posts", consumes = "application/json")
    Response getPosts();
}

  1. 从响应中获取 Request.url
Response response = apiClient.getPosts();
String url = response.request().url()

那么你就可以得到网址了

【讨论】:

    猜你喜欢
    • 2012-01-30
    • 2013-08-11
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 2022-10-02
    • 2011-04-07
    • 2010-11-04
    相关资源
    最近更新 更多