Feign Client相比Rest Template可以自動實現(xiàn)負載均衡,而且接口使用也更加友好,但是一般情況下Feign Client都需要依賴eureka吭狡。其實我們也可以在沒有eureka的環(huán)境下,直接使用Feign Client以故。既用到了Feign Client的好處,又為將來切換到Spring Cloud做好預(yù)備.
添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.netflix.archaius</groupId>
<artifactId>archaius-core</artifactId>
<version>0.7.6</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.1-jre</version>
</dependency>
定義Feign接口
HomeApi
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(value = "home", path = "/home")
public interface HomeApi {
@GetMapping("/ping")
String ping();
}
注意:這里的value = "home"
需要與后面配置文件中的home
一致
配置文件
application.yml
eureka:
client:
enabled: false
home:
ribbon:
listOfServers: http://localhost:8081
上面配置文件中home interface的目標地址是
http://localhost:8081
裆操,如果有多個的話怒详,可以使用逗號(,
)隔開
接口調(diào)用
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
執(zhí)行結(jié)果
標準輸出中輸出
success