Feign简单学习

Feign的作用

  Feign可以对Rest请求进行隐藏,将其伪装成类似StringMVC的Controller一样,大大的简化了代码中rest风格的远程调用,减少多次远程调用中的重复代码。

Feign的简单使用

  引入依赖

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

  application中加入@EnableFeignClients注解

@SpringCloudApplication
//feign自带负债均衡
@EnableFeignClients
public class CustomerApplication {
    public static void main(String[] args) {
        SpringApplication.run(CustomerApplication.class,args);
    }

//    @Bean
//    @LoadBalanced
//    public RestTemplate restTemplate1(){
//        return new RestTemplate();
//    }

}

  定义一个FeignClient接口,在该接口中配置远程调用的请求方式,请求地址,请求参数以及返回类型。(定义的接口,采用SpringMVC的注解,Feign会根据注解帮我们自动生成url,并进行访问,返回结果)

//请求地址的服务名称
@FeignClient("user-service")
public interface UserClient {
    //请求类型 get  请求地址的后半部分
    @GetMapping("user/{id}")
    //请求参数 返回类型
    String user(@PathVariable("id") Long id);
}

  在controller中注入FeignClient接口,并通过该接口进行远程调用

    @Autowired
    private UserClient client;
    @GetMapping("{id}")
    public String user(@PathVariable("id") Long id){
//        List<ServiceInstance> serviceInstanceList = client.getInstances("user-service");
//        return  restTemplate.getForObject("http://"+serviceInstanceList.get(0).getHost()+":"
//                + serviceInstanceList.get(0).getPort()+"/user/"+id,User.class);
//        return  restTemplate.getForObject("http://localhost:8081/user/"+id,User.class);
//        String url = "http://user-service/user/"+id;
//        return  restTemplate.getForObject(url,String.class);
        return client.user(id);
    }

Feign的其他用途

  1.Feign自带负载均衡,不用再做相关配置。

  2.Feign支持Hystrix,但Hystrix的使用方式有所不同。

   2.1 添加配置   

#feign中启动hystrix
feign:
  hystrix:
    enabled: true
#feign中连接超时时长和读取数据超时时长
ribbon:
  ConnectionTimeOut: 500
  ReadTimeOut: 2000

     2.2 新增一个fallback类,继承上面定义的UserClient接口,用来写降级处理的逻辑

//添加@Component注解,注入到Spring中去
@Component
public class UserClientFallback implements UserClient{
    @Override
    public String user(Long id) {
        return "很抱歉,目前服务器忙鸭,请稍后再试!";
    }
}

     2.3 在UserClient接口上,指定fallback类为上方定义的UserClientFallback 

//请求地址的服务名称
@FeignClient(value = "user-service",fallback = UserClientFallback.class)
public interface UserClient {
    //请求类型 get  请求地址的后半部分
    @GetMapping("user/{id}")
    //请求参数 返回类型
    String user(@PathVariable("id") Long id);
}

     2.4 上述操作做完后,所有通过UserClient 进行的远程请求都会受到hystrix的保护。

  3.Feign有log级别控制

  4.Feign可以对请求进行压缩处理(通常用在大文件请求或者响应时,会对请求进行GZIP压缩),减少通信过程中的性能损耗。 

feign:
  #开启压缩
  compression:
    request:
      enabled: true # 开启请求压缩
      #最小触发压缩的大小
      min-request-size: 2048
      #触发压缩数据类型,(注意不能使用"" ,'')
      mime-types: text/xml, application/xml, application/json
    response:
      enabled: true # 开启响应压缩
posted @ 2020-06-29 21:54  听风和  阅读(207)  评论(0)    收藏  举报