Spring Cloud OpenFeign教程

本文介绍Spring Cloud OpenFeign——构建Spring Boot应用的声明式Rest客户端。Feign使用可插入的注解更方便地写Web服务,它包括Feign注解和JAX_RS注解。

使用Feign的的优势是不需要为调用服务编写任何代码,只需编写接口定义。

增加依赖

首先创建Spring Boot web应用,在pom文件中增加 spring-cloud-starter-openfeign 依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

当然也要增加 spring cloutd的依赖:

 <dependencyManagement>
     <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Feign Client

在主类上增加注解 @EnableFeignClients

@SpringBootApplication
@EnableFeignClients
public class ExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }
}

使用该注解即启用扫描所有声明了Feign客户端的接口。

下面使用@FeignClient定义Feign client :

@FeignClient(value = "jplaceholder", url = "https://jsonplaceholder.typicode.com/")
public interface JSONPlaceHolderClient {

    @RequestMapping(method = RequestMethod.GET, value = "/posts")
    List<Post> getPosts();

    @RequestMapping(method = RequestMethod.GET, value = "/posts/{postId}", produces = "application/json")
    Post getPostById(@PathVariable("postId") Long postId);
}

上面示例配置使用客户端读取 JSONPlaceHolder APIs 。该网站提供了示例api,方便我们测试使用。

@FeignClient 注解的value参数是必须的,表示客户端名称。 url参数指定API 的基本 url。另外,既然该接口是Feign客户端,我们能使用Spring Web注解去声明我们想要访问的API。

配置

每个Feign客户端都有一组自定义组件构成,理解这点很重要。

Spring Cloud提供了一组缺省组件,我们可以定义配置类进行自定义各个组件。主要包括下面组件bean:

  • Decoder – ResponseEntityDecoder, 包装 SpringDecoder, 用于解析 Response
  • Encoder – SpringEncoder, 用于RequestBody编码
  • Logger – *Slf4jLogger 是Feign的缺省日志bean
  • Contract – SpringMvcContract, 提供注解处理
  • Feign-Builder – HystrixFeign.Builder 用于构建组件
  • Client – LoadBalancerFeignClient 为缺省 Feign client

自定义bean配置

如果需要自定义一个或多个bean,可以使用@Configuration 配置类,然后在@FeignClient注解上引用。下面示例告诉Feign使用 OkHttpClient 代替缺省bean用于支持HTTP/2。Feign支持多个客户端用于不同场景,包括ApacheHttpClient,它可以发送多个请求头信息,如 *Content-Length*。当然别忘了增加必要的依赖。

@Configuration
public class MyClientConfiguration {

    @Bean
    public OkHttpClient client() {
        return new OkHttpClient();
    }
}
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-okhttp</artifactId>
</dependency>

<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
</dependency>

最后修改@FeignClient注解:

@FeignClient(value = "jplaceholder",
  url = "https://jsonplaceholder.typicode.com/",
  configuration = MyClientConfiguration.class)

使用属性文件配置

处理配置类,还可以使用application属性文件配置Feign客户端,请看示例:

spring.application.name=openfeign
feign.client.config.default.connect-timeout=5000
feign.client.config.default.read-timeout=5000
feign.client.config.default.logger-level=basic

feign.client.default-config=jplaceholder

我们设置超时时间为5秒,对声明的客户端日志级别为basic。最后设置客户端缺省名称,前面使用注解*@FeignClient* 的。如果两者都配置了,那么使用属性文件优先级高。

支持Hystrix

Feign支持Hystrix,所以如果启用,可以实现回退模式。当远程服务调用失败,回退模式不是产生异常,而是执行替代代码路径尝试另一种执行操作。要启用回退模式,需在属性文件中增加配置 *feign.hystrix.enabled=true*

@Component
public class JSONPlaceHolderFallback implements JSONPlaceHolderClient {

    @Override
    public List<Post> getPosts() {
        return Collections.emptyList();
    }

    @Override
    public Post getPostById(Long postId) {
        return null;
    }
}

为了让Feign知道我们提供的回退方法,需要在@FeignClient注解中指定回退类:

@FeignClient(value = "jplaceholder",
  url = "https://jsonplaceholder.typicode.com/",
  fallback = JSONPlaceHolderFallback.class)
public interface JSONPlaceHolderClient {
    // APIs
}

日志

每个Feign客户端,缺省支持日志bean。为了启用日志,可以在 application.properties 中设置客户端接口的包名:

logging.level.com.baidu.cloud.openfeign.client: DEBUG

或者仅对特定包中的客户端启用日志,可以使用完整类名:

logging.level.com.baidu.cloud.openfeign.client.JSONPlaceHolderClient: DEBUG

注意Feign的logger.Level只对DEBUG做出响应。

总结

本文介绍了 Spring Cloud OpenFeign的使用方法,以及其一些列组件bean,我们示例中介绍了Hystrix和日志,另外还可以定义拦截器和错误处理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值