互联网项目---4(Hystrix熔断器,Feign远程调用,feign整合hystrix,ribbon)

4.Hystrix熔断器

4.1 简介

  • Hystrix是Netflix开源的一个延迟和容错库,用于隔离访问远程服务、第三方库,防止出现级联失败。

  • 当访问超时时,调用备选方案

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PdvX8ip6-1587635562746)(D:\tooss\JAVA学习文件\大二(1)]\笔记\第三阶段_互联网项目\总结\图片\图片2.png)

4.2 Hystrix入门

  • 步骤一: 导入pom依赖

  • 步骤二: 开启Hystrix熔断,添加@EnableHystrix 注解

  • 步骤三: 改造服务方,添加注解+备选方案

  • 步骤四: 改造提供方,模拟延迟

  • 步骤一: 导入pom依赖

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
    
  • 步骤二: 开启Hystrix熔断,添加@EnableHystrix 注解

    @SpringBootApplication
    @EnableEurekaClient
    @EnableHystrix      //开启熔断器
    public class ClientApplication {
        public static void main(String[] args) {
            SpringApplication.run(ClientApplication.class,args);
        }
    }
    
  • 步骤三: 改造服务方,添加注解+备选方案

    @Component
    public class DataDao {
        @Resource
        private RestTemplate restTemplate;
    	//添加注解并声明临时方案/默认超时1000毫秒
        @HystrixCommand(fallbackMethod = "dataFallback")
        public ResponseEntity<String> data(){
            //  获取访问用时,方便查看
            long start = System.currentTimeMillis();
            ResponseEntity<String> entity = restTemplate.getForEntity("http://service/test", String.class);
            long end = System.currentTimeMillis();
            System.out.println("访问用时:" + (end-start));
            return entity;
        }
    
        public ResponseEntity<String> dataFallback(){
            return ResponseEntity.ok("临时数据");
        }
    }
    
    • 多学一点:通过@HystrixCommand的commandProperties 可以设置超时时间

      // HystrixCommandProperties Hystrix命令参数配置类
      @HystrixCommand(fallbackMethod = "dataFallback",commandProperties = @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1000"))
      
  • 步骤四: 改造提供方,模拟延迟

    @RestController
    @RequestMapping("/test")
    public class TestController {
    
        @GetMapping
        public ResponseEntity<String> test(HttpServletRequest request) throws InterruptedException {
            //让线程睡一会,模拟延迟
            Thread.sleep(new Random().nextInt(2000));
            return ResponseEntity.ok("测试数据" + request.getServerPort());
        }
        
    }
    
  • 步骤五: 测试数据

4.2 面试题

  • Ribbon负载均衡重试机制和Hystrix熔断器谁先执行
    • 当超时时间相同时,熔断器先执行
    • 当超时时间不同时,超时时间小的先执行
    • 如果两个都需要配置,重试机制的超时时间 小于 熔断器

5. Feign远程调用

5.1 简介

  • Feign是一种声明式、模板化的HTTP客户端,本质上是远程调用。
  • 在SpringCloud中使用Feign,我们可以做到使用HTTP请求远程服务时能与调用本地方法一样的编码体验

5.2 Feign入门

  • 步骤一: 导入pom依赖

  • 步骤二: 开启Feign,添加注解

  • 步骤三: 创建接口类DataFeign,并声明服务名和访问路径

  • 步骤四: 修改controller,调用DataFeign

  • 步骤一: 导入pom依赖

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    
  • 步骤二: 开启Feign,添加注解

    @SpringBootApplication
    @EnableEurekaClient
    @EnableHystrix      //开启熔断器
    @EnableFeignClients //开启feign
    public class ClientApplication {
        public static void main(String[] args) {
            SpringApplication.run(ClientApplication.class,args);
        }
    }
    
  • 步骤三: 创建接口类DataFeign,并声明服务名和访问路径

    • 通过@FeignClient 声明Feign客户端。

      • value : 用于设置服务名称
      • path:用于设置路径前缀(也就是controller配置的路径)
    • Feign中的方法需要与服务的方法声明完全一致。注意:路径

    • Feign会根据注解帮我们生成URL。

      package com.czxy.feign;
      
      import org.springframework.cloud.openfeign.FeignClient;
      import org.springframework.http.ResponseEntity;
      import org.springframework.web.bind.annotation.GetMapping;
      
      /**
       * Created by 澈 on 2019/12/11.
       */
      @FeignClient(value = "service",path = "/test")
      public interface DataFeign {
      
          @GetMapping
          ResponseEntity<String> testDemo01();
      }
      
      
  • package com.czxy.feign;
    
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    
    import javax.servlet.http.HttpServletRequest;
    
    /**
     * Created by liangtong.
     */
    @FeignClient(value="service4",path="/test")
    public interface DataFeign {
    
        @GetMapping
        public ResponseEntity<String> test() ;
    }
    
  • 步骤四: 修改controller,调用DataFeign

    package com.czxy.controller;
    
    import com.czxy.dao.DataDao;
    import com.czxy.feign.DataFeign;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.annotation.Resource;
    
    /**
     * Created by liangtong.
     */
    @RestController
    @RequestMapping("/data")
    public class DataController {
        @Resource
        //private DataDao dataDao;
        private DataFeign dataFeign;
    
        @GetMapping
        public ResponseEntity<String> data(){
            //return dataDao.data();
            return dataFeign.test();
        }
    }
    

5.3 Feign整合Ribbon

  • Feign中本身已经集成了Ribbon依赖,不需要额外引入依赖和注解@LoadBalanced,就可以完成负载均衡处理。

  • 直接添加配置信息就可以启动Ribbon重试机制

    # Ribbon负载均衡策略,默认轮换
    service:  #服务提供方服务名
      ribbon:
    #    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule                   #随机
    #    NFLoadBalancerRuleClassName : com.netflix.loadbalancer.BestAvailableRule           #并发最少
    #    NFLoadBalancerRuleClassName : com.netflix.loadbalancer.WeightedResponseTimeRule    #请求时间权重
        ConnectTimeout: 250               # Ribbon的连接超时时间
        ReadTimeout: 1000                 # Ribbon的数据读取超时时间
        OkToRetryOnAllOperations: true  # 是否对所有操作都进行重试
        MaxAutoRetriesNextServer: 1     # 切换实例的重试次数
        MaxAutoRetries: 1               # 对当前实例的重试次数
    

5.4 Feign整合Hystrix

  • Feign默认也有对Hystix的集成,只不过,默认情况下是关闭的。

  • 步骤一: 在yml中开启Hystrix

    feign:
      hystrix:
        enabled: true          #开启hystrix
    
  • 步骤二: 创建一个DataFeign接口的实现类

    • @FeignClient(value=“服务名”,path=“前缀路径”,fallback=备选方案类.class)
    package com.czxy.feign;
    
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Component;
    
    /**
     * Created by 澈 on 2019/12/12.
     */
    @Component
    public class FallBackDataFeign implements DataFeign {
    
        @Override
        public ResponseEntity<String> testDemo01() {
            return ResponseEntity.ok("临时数据");
        }
    }
    
  • 步骤三: 在DataFeign中,指定刚才编写的实现类

    package com.czxy.feign;
    
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    
    /**
     * Created by 澈 on 2019/12/11.
     */
    //在fallback中声明实现类
    @FeignClient(value = "service",path = "/test",fallback = FallBackDataFeign.class)
    public interface DataFeign {
    
        @GetMapping
        ResponseEntity<String> testDemo01();
    }
    

5.5 请求压缩

  • Spring Cloud Feign 支持对请求和响应进行GZIP压缩,以减少通信过程中的性能损耗。
  • 通过下面的参数即可开启请求与响应的压缩功能:以及触发压缩的大小下限进行设置
feign:
  compression:
    request:
      enabled: true # 开启请求压缩
      mime-types: text/html,application/xml,application/json # 设置压缩的数据类型
      min-request-size: 2048 # 设置触发压缩的大小下限
    response:
      enabled: true # 开启响应压缩
发布了31 篇原创文章 · 获赞 0 · 访问量 181

猜你喜欢

转载自blog.csdn.net/weixin_46759279/article/details/105713387