Spring Cloud 声明式REST客户端 OpenFeign -- 1. 如何包含Feign

本文介绍如何在SpringBoot项目中整合Feign实现微服务间的调用,包括添加依赖、定义Feign客户端及配置负载均衡,适用于SpringBoot2.1.2和SpringCloudGreenwich版本。

本文内容基于 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值