【六】Feign远程调用组件

Feign简介

Feign是Netflix开发的⼀个轻量级RESTful的HTTP服务客户端(⽤它来发起请求,远程调⽤的),是以Java接⼝注解的⽅式调⽤Http请求,⽽不⽤像Java中通过封装HTTP请求报⽂的⽅式直接调⽤,Feign被⼴泛应⽤在Spring Cloud 的解决⽅案中。

类似于Dubbo,服务消费者拿到服务提供者的接口,然后像调⽤本地接口方法⼀样去调⽤,实际发出的是远程的请求。

  • Feign可帮助我们更加便捷,优雅的调⽤HTTP API:不需要我们去拼接url然后呢调用restTemplate的api,在SpringCloud中,使⽤Feign⾮常简单,创建⼀个接⼝(在消费者–服务调⽤⽅这⼀端),并在接⼝上添加⼀些注解,代码就完成了
  • SpringCloud对Feign进⾏了增强,使Feign⽀持了SpringMVC注解(OpenFeign)

Feign配置应用

在服务调⽤者⼯程(消费)创建接⼝(添加注解)
(效果)Feign = RestTemplate+Ribbon+Hystrix

  • 服务消费者⼯程中引⼊Feign依赖(或者⽗类⼯程)
  • 服务消费者⼯程启动类使⽤注解@EnableFeignClients添加Feign⽀持
  1. 在m-parent的基础上新建module mvn 项目m-service-autodeliver-8092
    在这里插入图片描述

  2. 导入依赖

  <!--eureka client 客户端依赖引入-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
  1. 启动类
@SpringBootApplication
@EnableDiscoveryClient //开启服务注册与发现
@EnableFeignClients //开启FeignClients
public class AutodeliverApplication8092 {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(AutodeliverApplication8092.class, args);
    }
}
  1. application.yml
server:
  port: 8092

spring:
  application:
    name: m-service-autodeliver

#注册发现
eureka:
  client:
    service-url:
      defaultZone: http://CloudEurekaServerA:8761/eureka,http://CloudEurekaServerB:8762/eureka
    # 每隔多久拉取⼀次服务列表
    registry-fetch-interval-seconds: 30
  instance:
    prefer-ip-address: true
    instance-id: ${
    
    spring.cloud.client.ip-address}:${
    
    spring.application.name}:${
    
    server.port}:@project.version@
    # 租约续约间隔时间,默认30秒
    lease-renewal-interval-in-seconds: 30
    # 租约到期,服务时效时间,默认值90秒,服务超过90秒没有发⽣⼼跳,EurekaServer会将服务从列表移除
    lease-expiration-duration-in-seconds: 90

5.创建ResumeFeignClient接口

@FeignClient(name = "m-service-resume")
@RequestMapping("/resume")
public interface ResumeFeignClient {
    
    
//    @RequestMapping(value = "/resume/openstate/{userId}",method= RequestMethod.GET)
    @GetMapping("/openstate/{userId}")
    public Integer findDefaultResumeState(@PathVariable Long userId);


}
  1. 改造AutodeliverController
@RestController
@RequestMapping("/autodeliver")
public class AutodeliverController {
    
    
    @Autowired
    private ResumeFeignClient resumeFeignClient;

    /**
     * 使用Feign
     *
     * @param userId
     * @return
     */
    @GetMapping("/checkState/{userId}")
    public Integer findResumeOpenState(@PathVariable Long userId) {
    
    
        Integer defaultResumeState = resumeFeignClient.findDefaultResumeState(userId);
        System.out.println("======>>>调⽤微服务,获取到⽤户" + userId + "的默认     简历当前状态为:" + defaultResumeState);
        return defaultResumeState;
    }
}
  1. 启动,访问http://localhost:8092/autodeliver/checkState/1545132
    在这里插入图片描述

Feign 对Ribbon的支持

Feign 本身已经集成了Ribbon依赖和⾃动配置,因此我们不需要额外引⼊依赖,可以通过 ribbon.xx 来进 ⾏全局配置,也可以通过服务名.ribbon.xx 来对指定服务进⾏细节配置配置

#针对的被调⽤⽅微服务名称,不加就是全局⽣效
m-service-autodeliver:
  ribbon:
    #请求连接超时时间
    ConnectTimeout: 2000
    #请求处理超时时间
    ReadTimeout: 5000
    #对所有操作都进⾏重试
    OkToRetryOnAllOperations: true
    ####根据如上配置,当访问到故障请求的时候,它会再尝试访问⼀次当前实例(次数由MaxAutoRetries配置),
    ####如果不⾏,就换⼀个实例进⾏访问,如果还不⾏,再换⼀次实例访问(更换次数由MaxAutoRetriesNextServer配置),
    ####如果依然不⾏,返回失败信息。
    MaxAutoRetries: 0 #对当前选中实例重试次数,不包括第⼀次调⽤
    MaxAutoRetriesNextServer: 0 #切换实例的重试次数
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule #负载策略调整

Feign 日志

Feign是http请求客户端,类似于咱们的浏览器,它在请求和接收响应的时候,可以打印出⽐较详细的⼀些⽇志信息(响应头,状态码等等)

  1. 开启Feign⽇志功能及级别
// Feign的⽇志级别(Feign请求过程信息)
// NONE:默认的,不显示任何⽇志----性能最好
// BASIC:仅记录请求⽅法、URL、响应状态码以及执⾏时间----⽣产问题追踪
// HEADERS:在BASIC级别的基础上,记录请求和响应的header
// FULL:记录请求和响应的header、body和元数据----适⽤于开发及测试环境定位问题
@Configuration
public class FeignConfig {
    
    
 @Bean
 Logger.Level feignLevel() {
    
    
 return Logger.Level.FULL;
 }
}

  1. 配置log⽇志级别为debug
logging:
  level:
    # Feign⽇志只会对⽇志级别为debug的做出响应
    com.w.edu.client.ResumeFeignClient: debug

在这里插入图片描述

Feign对熔断器的⽀持

  • 在Feign客户端⼯程配置⽂件(application.yml)中开启Feign对熔断器的⽀持
# 开启Feign的熔断功能
feign:
  hystrix:
    enabled: true

1)开启Hystrix之后,Feign中的⽅法都会被进⾏⼀个管理了,⼀旦出现问题就进⼊对应的回退逻辑处理
2)针对超时这⼀点,当前有两个超时时间设置(Feign/hystrix),熔断的时候是根据这两个时间的最
⼩值来进⾏的,即处理时⻓超过最短的那个超时时间了就熔断进⼊回退降级逻辑

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            ##########################################Hystrix的超时时长设置
            timeoutInMilliseconds: 15000
  • ⾃定义FallBack处理类(需要实现FeignClient接⼝)
@Component 
public class ResumeFallback implements ResumeServiceFeignClient {
    
    
 @Override
 public Integer findDefaultResumeState(Long userId) {
    
    
 return -6;
 }
}
  • 在@FeignClient注解中关联2)中⾃定义的处理类
@FeignClient(name = "m-service-resume",fallback = ResumeServiceFeignClientFallback.class)
public interface ResumeFeignClient {
    
    
    @RequestMapping(value = "/resume/openstate/{userId}",method= RequestMethod.GET)
    public Integer findDefaultResumeState(@PathVariable Long userId);


}

Feign对请求压缩和响应压缩的支持

feign:
  compression:
    request:
      enabled: true
      mime-types: text/html,application/xml,application/json # 设置压缩的数据类
    response:
      enabled: true

猜你喜欢

转载自blog.csdn.net/u014535922/article/details/129960365