根据环境定义不同的 Feign 客户端实现

2024-03-16

我有一个 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();
}

Service

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成员变量在MyService属于类型

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

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

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


解决方案如下:

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 
{}

最后,在您的服务实现中:

@Resource
private FeignBase feignBase;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据环境定义不同的 Feign 客户端实现 的相关文章

随机推荐