本文内容基于 Spring boot 2.1.2 RELEASE + Spring Cloud Greenwich.RELEASE
要在项目中包含Feign,需要使用如下starter :
<!--添加feign依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- feign 又需要进行负载均衡,使用到 ribbon, 所以这里也要引入下面的依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
- 例子
Spring boot应用
@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Feign客户端定义StoreClient.java
@FeignClient("stores")
public interface StoreClient {
@RequestMapping(method = RequestMethod.GET, value = "/stores")
List<Store> getStores();
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
Store update(@PathVariable("storeId") Long storeId, Store store);
}
在@FeignClient注解中,字符串值stores是给feign客户端起的名字,可以随意起,这个名称会被用作创建Ribbon负载均衡器。你也可以为url属性指定一个URL值(URL绝对路径或者只有一个主机名)。应用上下文中feign客户端bean名称是接口的长名称(这里注意区分"feign客户端bean名称"和"feign客户端名称"是两个不同的概念)。如果想给feign客户端起别名,可以使用注解@FeignClient的属性qualifier。
上面提到的Ribbon负载均衡器会尝试发现这里stores服务对应的物理地址(可能是多个)。如果你的应用是一个Eureka客户端,它会使用Eureka服务注册表解析该服务。如果你不想使用Eureka,你也可以在外部配置文件中配置一组服务器,比如在application.yml文件中提供这样的配置 :
# 不使用服务发现机制时的Feign配置
stores:
ribbon:
listOfServers: 192.168.1.100:8080,192.168.1.101:8080
本文介绍如何在SpringBoot项目中整合Feign实现微服务间的调用,包括添加依赖、定义Feign客户端及配置负载均衡,适用于SpringBoot2.1.2和SpringCloudGreenwich版本。
1464

被折叠的 条评论
为什么被折叠?



