7

我有一个 Spring Boot 应用程序,它使用 Feign 通过 Eureka 调用外部 Web 服务。我希望能够使用 Feign 接口的模拟实现来运行应用程序,这样我就可以在本地运行应用程序,而不必运行 Eureka 或外部 Web 服务。我曾设想定义一个允许我执行此操作的运行配置,但我正在努力让它发挥作用。问题是无论我尝试什么,Spring 的“魔法”都在为 Feign 接口定义一个 bean。

假装界面

@FeignClient(name = "http://foo-service")
public interface FooResource {
    @RequestMapping(value = "/doSomething", method = GET)
    String getResponse();
}

服务

public class MyService {
    private FooResource fooResource;

    ...

    public void getFoo() {
        String response = this.fooResource.getResponse();
        ...
    }
}

我尝试添加一个配置类,如果 Spring 配置文件是“本地”,则有条件地注册一个 bean,但是当我使用该 Spring 配置文件运行应用程序时从未调用过它:

@Configuration
public class AppConfig {
    @Bean
    @ConditionalOnProperty(prefix = "spring.profile", name = "active", havingValue="local")
    public FooResource fooResource() {
        return new FooResource() {
            @Override
            public String getResponse() {
                return "testing";
            }
        };
    }
}

在我的服务运行时,FooResource成员变量 inMyService是类型

HardCodedTarget(type=FoorResource, url= http://foo-service )

根据 IntelliJ。这是由 Spring Cloud Netflix 框架自动生成的类型,因此会尝试与远程服务进行实际通信。

有没有一种方法可以根据配置设置有条件地覆盖 Feign 接口的实现?

4

3 回答 3

6

解决方案如下:

public interface FeignBase {
   @RequestMapping(value = "/get", method = RequestMethod.POST, headers = "Accept=application/json")
   Result get(@RequestBody Token common);
}

然后定义基于 env 的接口:

@Profile("prod")
@FeignClient(name = "service.name")
public interface Feign1 extends FeignBase 
{}

@Profile("!prod")
@FeignClient(name = "service.name", url = "your url")
public interface Feign2 extends FeignBase 
{}

最后,在您的服务 impl 中:

@Resource
private FeignBase feignBase;
于 2019-09-13T14:37:05.687 回答
3

Spring Cloud Netflix github 存储库上发布了相同的问题后,一个有用的答案是使用 Spring@Profile注释。

我创建了一个没有用 注释的替代入口点类@EnabledFeignClients,并创建了一个新的配置类,它为我的 Feign 接口定义了实现。现在,这允许我在本地运行我的应用程序,而无需运行 Eureka 或任何依赖服务。

于 2017-05-15T15:14:43.500 回答
1

我正在使用一个更简单的解决方案来避免像 url 这样的可变参数有多个接口。

    @FeignClient(name = "service.name", url = "${app.feign.clients.url}")
    public interface YourClient{}

应用程序-{profile}.properties

app.feign.clients.url=http://localhost:9999
于 2020-03-31T09:25:21.673 回答