@FeignClient同一个服务name实现多个接口配置类的解决方案

问题

Feign有一个局限性,即对于同一个service-id只能使用一个配置类,如果有多个@FeignClient注解使用了相同的name属性,则注解的configuration参数会被覆盖。至于谁覆盖谁要看Spring容器初始化Bean的顺序。

解决方案

  1. 添加配置(spring.main.allow-bean-definition-overriding=true)。这样允许同名的bean存在,但是不安全,不推荐。(来自网络,未测试)

  2. 在openfeign2.1.x 以上版本中@FeignClient里面添加了新属性ContextId,这样使用这个属性也是可以的,官网有这个例程。(https://cloud.spring.io/spring-cloud-openfeign/reference/html/#creating-feign-clients-manually)

  3. 官网提供的另外一种就是手动创建Feign客户端,如下就是,(官网:https://cloud.spring.io/spring-cloud-openfeign/reference/html/#spring-cloud-feign-hystrix-fallback)
    `@Import(FeignClientsConfiguration.class)
    class FooController {

    private FooClient fooClient;

    private FooClient adminClient;

    @Autowired
    

    public FooController(Decoder decoder, Encoder encoder, Client client, Contract contract) {
    this.fooClient = Feign.builder().client(client)
    .encoder(encoder)
    .decoder(decoder)
    .contract(contract)
    .requestInterceptor(new BasicAuthRequestInterceptor(“user”, “user”))
    .target(FooClient.class, “https://PROD-SVC”);

    this.adminClient = Feign.builder().client(client)
            .encoder(encoder)
            .decoder(decoder)
            .contract(contract)
            .requestInterceptor(new BasicAuthRequestInterceptor("admin", "admin"))
            .target(FooClient.class, "https://PROD-SVC");
    

    }
    `

Spring Cloud中,可以使用@FeignClient注解来调用远程服务接口。@FeignClient注解是一个声明式的Web服务客户端,可以将一个服务接口定义成Java接口,然后使用注解的方式来调用远程服务。 具体步骤如下: 1. 引入Feign依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> ``` 2. 创建服务接口 创建一个Java接口,用于定义远程服务接口方法。例如: ``` @FeignClient(name = "remote-service") public interface RemoteService { @GetMapping("/hello") String sayHello(); } ``` @FeignClient注解中的name属性指定了远程服务的名称,这个名称对应了服务注册中心中的服务名。 3. 调用远程服务 在需要调用远程服务的地方,通过@Autowired注入RemoteService接口实例,然后直接调用接口中的方法即可。 ``` @RestController public class MyController { @Autowired private RemoteService remoteService; @GetMapping("/test") public String test() { return remoteService.sayHello(); } } ``` 在上面的例子中,MyController通过调用RemoteService接口中的sayHello()方法来调用远程服务中的/hello接口。 需要注意的是,@FeignClient注解默认使用的是Spring MVC注解,因此在定义服务接口方法时需要使用Spring MVC的注解来指定请求方式、请求路径等信息。例如,在RemoteService接口中的sayHello()方法上使用@GetMapping注解来指定使用GET请求访问/hello接口
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值