藏兵谷JAVAcloud组件

SpringCloud微服务之服务调用Feign

2019-11-12  本文已影响0人  iDevOps

前面我们学习了使用Ribbon,大大简化了远程调用时的代码

# ribbon远程调用服务
restTemplate.getForObject("http://eureka-client-user/hello", String.class);

我们思考下,还有没有更优雅的方式呢?
这就是我们接下来要学习的Feign。

Feign简介

feign的中文翻译是假装、伪装的意思。
它可以把Rest请求进行隐藏,伪装成类似SpringMVC的Controller一样,让你可以不用拼接url,这些Feign都帮你来完成。

快速入门
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>2.0.1.RELEASE</version>
</dependency>
/**
 * @FeignClient: 声明这是一个Feign客户端
 * value : 指定服务名称
 * fallback : 熔断错误处理类
 * 接口中的定义方法,完全采用SpringMVC的注解,Feign会根据注解帮我们生成URL,并访问获取结果
 */
@FeignClient(value = "eureka-client-user", fallback = UserFeignClientFallback.class)
public interface UserFeignClient {

    @GetMapping("/hello")
    String hello();

}
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class FeignApplication {

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

}
feign:
  hystrix:
    enabled: true # 开启Feign的熔断功能
# fallback处理类
@Component
public class UserFeignClientFallback implements UserFeignClient {
    @Override
    public String hello() {
        return "error";
    }
}
eureka-client-user:
  ribbon:
    ConnectTimeout: 250 # 连接超时时间(ms)
    ReadTimeout: 1000 # 通信超时时间(ms)
    OkToRetryOnAllOperations: true # 是否对所有操作重试
    MaxAutoRetriesNextServer: 1 # 同一服务不同实例的重试次数
    MaxAutoRetries: 1 # 同一实例的重试次数

到这里就配置好了,可以测试了。

Feign的其他功能(了解)
feign:
  compression:
    request:
      enabled: true # 开启请求压缩
    response:
      enabled: true # 开启响应压缩

同时,我们也可以对请求的数据类型,以及触发压缩的大小下限进行设置

feign:
  compression:
    request:
      enabled: true # 开启请求压缩
      mime-types: text/html,application/xml,application/json # 设置压缩的数据类型
      min-request-size: 2048 # 设置触发压缩的大小下限
上一篇下一篇

猜你喜欢

热点阅读