spring cloud 学习(Feign)分布式配置中心

spring clound 之 Feign

Feign 是一个声明式的 REST 客户端,它用了基于接口的注解方式,很方便实现客户端配置。

是一个简化了RestTemplate调用以及 Ribbon的组件

1、操作步骤

  1. 导入依赖
    1. <!--feign-->
              <dependency>
      
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-openfeign</artifactId>
      
              </dependency>
  2. 启动类上添加注解 @EnableFeignClients //开启Feign的功能 
    1.  1 @EnableDiscoveryClient // 激活DiscoveryClient
       2 @EnableEurekaClient
       3 @SpringBootApplication
       4 
       5 @EnableFeignClients //开启Feign的功能
       6 public class ConsumerApp {
       7     public static void main(String[] args) {
       8         SpringApplication.run(ConsumerApp.class,args);
       9     }
      10 }

      其余注解不能删除,都是基于Eureka来使用的 

  3. 编写feign接口
    1.  1 /**
       2  *
       3  * feign声明式接口。发起远程调用的。
       4  *
       5  String url = "http://FEIGN-PROVIDER/goods/findOne/"+id;
       6  Goods goods = restTemplate.getForObject(url, Goods.class);
       7  *
       8  * 1. 定义接口
       9  * 2. 接口上添加注解 @FeignClient,设置value属性为 服务提供者的 应用名称
      10  * 3. 编写调用接口,接口的声明规则 和 提供方接口保持一致。
      11  * 4. 注入该接口对象,调用接口方法完成远程调用
      12  */
      13 @FeignClient(value = "FEIGN-PROVIDER")
      14 public interface GoodsFeignClient {
      15     @GetMapping("/goods/findOne/{id}")
      16     public Goods findGoodsById(@PathVariable("id") int id);
      17 }

      满足的是将usrl进行拼接,能够直接使用,提高复用性

  4. controller中的方法进行修改
    1.  1 @RestController
       2 @RequestMapping("/order")
       3 public class OrderController {
       4 
       5     @Autowired
       6     private GoodsFeignClient goodsFeignClient;
       7 
       8     @GetMapping("/goods/{id}")
       9     public Goods findGoodsById(@PathVariable("id") int id){
      10 
      11         Goods goods = goodsFeignClient.findGoodsById(id);
      12 
      13         return goods;
      14     }
      15 }

       

2、Feign的超时设置

 Feign底层依赖于Ribbon实现负载均衡和远程调用

  Ribbon默认1s超时

 消费方进行配置

1 # 设置Ribbon的超时时间
2 ribbon:
3 
4   ConnectTimeout: 1000 # 连接超时时间 默认1s  默认单位毫秒
消费方与提供发连接的时间
5 6 ReadTimeout: 3000 # 逻辑处理的超时时间 默认1s 默认单位毫秒
可以理解为 提供方执行需要执行的代码的所有时间,直到返回一个值给 消费方

feign也具有超时时间,底层依赖Ribbon 所以直接用Ribbon进行设置

3、Feign 的日志记录

Feign 只能记录debug级别的日志

操作步骤

  1.配置

# 设置当前的日志级别 debug,feign只支持记录debug级别的日志

logging:

  level:

    com.itheima: debug

  2.定义Feign日志级别Bean

 1 @Configuration
 2 public class FeignLogConfig {
 3     /*
 4         NONE,不记录
 5         BASIC,记录基本的请求行,响应状态码数据
 6         HEADERS,记录基本的请求行,响应状态码数据,记录响应头信息
 7         FULL;记录完成的请求 响应数据
 8      */
 9     @Bean
10     public Logger.Level level(){
11         return Logger.Level.FULL;
12     }
13 }

  3.feign的配置类进行启用

@FeignClient(value = "FEIGN-PROVIDER",configuration = FeignLogConfig.class)
public interface GoodsFeignClient {

    @GetMapping("/goods/findOne/{id}")
    public Goods findGoodsById(@PathVariable("id") int id);

}

 

posted @ 2020-10-13 20:53  幸运超市  阅读(227)  评论(0编辑  收藏  举报