笔记10:Spring Cloud Feign

  1. Feign的配置
    1)pom

    <!-- 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>
    

    2)application.yml

    server:
      port: 8092
    
    #注册到Eureka服务中心
    eureka:
      client:
        service-url:
          defaultZone: http://CloudEurekaServerA:8761/eureka,http://CloudEurekaServerB:8762/eureka
      instance:
        prefer-ip-address: true 
        instance-id: ${
          
          spring.cloud.client.ip-address}:${
          
          spring.application.name}:${
          
          server.port}:@project.version@
    
    spring:
      application:
        name: service-consumer
    
    # springboot中暴露健康检查等断点接口
    management:
      endpoints:
        web:
          exposure:
            include: "*"
      # 暴露健康接口的细节
      endpoint:
        health:
          show-details: always
    

    3)启动类

    /**
    	 * @author Lossdate
    	 *
    	 * EnableFeignClients : 开启Feign客户端功能
    	 */
    	@SpringBootApplication
    	@EnableDiscoveryClient
    	@EnableFeignClients
    	public class CumsumerApplication8096 {
          
          
    	
    	    public static void main(String[] args) {
          
          
    	        SpringApplication.run(CumsumerApplication8096 .class, args);
    	    }
    	
    	}
    

    4)controller

    @RestController
    @RequestMapping("/autoDeliver")
    public class ConsumerController {
          
          
    
        private final ProviderServiceFeignClient providerServiceFeignClient;
    
        @Autowired
        public ConsumerController (ProviderServiceFeignClient providerServiceFeignClient) {
          
          
            this.providerServiceFeignClient= providerServiceFeignClient;
        }
    
        /**
         * 使用Ribbon负载均衡
         */
        @GetMapping("/checkState/{userId}")
        public Integer findOpenState(@PathVariable Long userId) {
          
          
    
            return providerServiceFeignClient.findOpenState(userId);
        }
    }
    

    5)service

    /**
     * @author lossdate
     * 原来:http://service-provider/provider/openstate/ + userId;
     * FeignClient表明当前类是一个Feign客户端,value指定该客户端要请求的服务名称(登记到注册中心上的服务提供者的服务名称)
     */
    @FeignClient(value = "service-provider")
    @RequestMapping("/provider")
    public interface ProviderServiceFeignClient {
          
          
    
        /**
         * Feign要做的事情就是,拼装url发起请求
         * 调用该方法就是调用本地接口方法,那么实际上做的是远程请求
         * 方法名和参数对应远程方法的方法名和参数
         */
        @GetMapping("/openstate/{userId}")
        public Integer findDefaultState(@PathVariable("userId") Long userId);
    
    }
    
  2. Feign对负载均衡的⽀持

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

    1)application.yml

    #日志
    logging:
      level:
        # Feign⽇志只会对⽇志级别为debug的做出响应
        com.lossdate.controller.service.ProviderServiceFeignClient: debug
    

    2)config

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

    #开启Feign的熔断功能
    feign:
      hystrix:
        enabled: true
    hystrix:
      command:
        default:
          execution:
            isolation:
              thread:
                ##########################################Hystrix的超时时⻓设置
                timeoutInMilliseconds: 5000
    

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

    /**
     * @author Lossdate
     *
     * 降级回退逻辑需要定义一个类,实现FeignClient接口,实现接口中的方法
     */
    @Component
    public class ProviderFallback implements ProviderServiceFeignClient {
          
          
        @Override
        public Integer findDefaultState(Long userId) {
          
          
            return -6;
        }
    }
    

    3)service修改

    //使⽤fallback的时候,类上的@RequestMapping的url前缀限定,改成配置在@FeignClient的path属性中
    @FeignClient(value = "service-provider", fallback = ProviderFallback.class, path = "/provider")
    //@RequestMapping("/provider")
    

猜你喜欢

转载自blog.csdn.net/Lossdate/article/details/114048020