Feign Client without Eureka(openfeign 3)
最近项目中用到了很多的远程调用,但是还不准备上微服务,但是feign client提供的对远程调用的封装还是很好用的,所以决定引用。 参考之前写的文章 Feign Client without Eureka ,发现升级到openfeign 3.1.7后并不能兼容,一直收到异常
feign.FeignException$ServiceUnavailable: [503] during [POST] to [XXX]: [Load balancer does not contain an instance for the service XXX]
。本文介绍了升级openfeign 3之后的使用方法。添加依赖:
pom.xml
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.7.12</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>3.1.7</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-loadbalancer</artifactId> <version>3.1.6</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies>
定义Feign接口
HomeApi
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; @FeignClient(name = "home", path = "/home") public interface HomeApi { @GetMapping("/ping") String ping();
注意:这里的
name = "home"
需要与后面配置文件中的home
一致application.yml
# 配置home的URI spring: cloud: discovery: client: simple: instances: home: uri: http://localhost:8081
上面配置文件中home interface的目标地址是一个数组
FeignWithoutEurekaApplication
import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; import javax.annotation.Resource; @EnableFeignClients @SpringBootApplication public class FeignWithoutEurekaApplication implements ApplicationRunner { @Resource private HomeApi homeApi; public static void main(String[] args) { SpringApplication.run(FeignWithoutEurekaApplication.class, args); @Override public void run(ApplicationArguments args) throws Exception { System.out.println(homeApi.ping());
注意需要添加注解
@EnableFeignClients
标准输出中输出
success
feign.FeignException$ServiceUnavailable: [503] during [POST] to [XXX]: [Load balancer does not contain an instance for the service XXX]
:
不能使用老的这种配置home: ribbon: listOfServers: http://localhost:8081
而是该用如下配置方法
spring: cloud: discovery: client: simple: instances: home: uri: http://localhost:8081
Feign Client without Eureka