springcloud第二天

59 阅读4分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第7天,点击查看活动详情

Ribbon组件

image-20200919141011321.png

IRule:制定负载均衡策略

Ping: 心跳机制,用于检测服务是否健康

ServerList: 包含所有的服务列表

ServerListFilter:包含的是满足过滤规则的服务列表

ServerListUpdater: 更新的服务列表

LoadBalancer: 负责调度

五、Hystrix

image-20200919141228566.png

1. 介绍

图标是豪猪,近亲---》老鼠。满身有刺,刺起到了保护作用。hystrix是netfilx公司出品的一个容错库,可以提供服务的降级与熔断。

2. 雪崩效应

image-20200919154623080.png

由于下游服务发生异常导致上游服务级联失败的情况就称为是雪崩效应

3. 熔断器使用

改造消费者步骤:

  1. 整合熔断器依赖
  2. 在启动类开启熔断器支持
  3. 修改consumerController编写默认的服务降级方法

过程:

  • 导入依赖

    <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
    
  • 启动开启熔断器支持

    /*
    @SpringBootApplication
    @EnableEurekaClient //声明是一个eureka客户端 ---》@EnableDiscoveryClient
    @EnableDiscoveryClient:支持的注册中心有:eureka/zk/nacos/apollo
    @EnableEurekaClient: 仅支持eureka注册中心
    @EnableCircuitBreaker //开启熔断器的支持
    */@SpringCloudApplication //一个顶三
    public class ConsumerServiceApplication {
        public static void main(String[] args) {
            SpringApplication.run(ConsumerServiceApplication.class, args);
        }
        @Bean
        @LoadBalanced //使用ribbon进行负载调用
        public RestTemplate restTemplate(){
            return new RestTemplate();
        }
    }
    ​
    
  • 编写默认熔断方法

    • 返回值类型必须与原方法类型一致
    • 参数列表必须与原方法一致
    •     
      @GetMapping("findUserById/{id}")
          @HystrixCommand(fallbackMethod = "fallback")
          public User findUserById(@PathVariable Integer id){
              //........
          }
      ​
      ​
      /**
           * @Author: guodong
           * @Date: 15:59 2020/9/19
           * @Parms [id]
           * @ReturnType: com.itheima.pojo.User
           * @Description: 默认服务降级方法
           *                      1.返回值类型必须与原方法一致
           *                      2.参数列表必须与原方法一致
          */
          public User fallback(Integer id){
              User user = new User();
              user.setId(id);
              user.setNote("默认服务降级方法...");
              return user;
          }
      
4. 扩展使用(了解即可,一般不使用)
@RestController
@RequestMapping("consumer")
@DefaultProperties(defaultFallback = "defaultFall")
public class ConsumerController {
​
    @Autowired
    private RestTemplate restTemplate;
    /*
        可以根据服务的应用名称从注册中心将服务的列表(ip+port)拉取下来
     */
    @Autowired
    private DiscoveryClient discoveryClient;
​
    @GetMapping("findUserById/{id}")
    //@HystrixCommand(fallbackMethod = "fallback")
    @HystrixCommand
    public User findUserById(@PathVariable Integer id){
​
        //第一次的url
        /*
            1.写死了---》url硬编码----》Eureka注册中心解决
            2.无法完成服务的负载均衡调用-----》Ribbon负载调用解决
            3.消费者服务无法感知用户服务的状态,导致用户服务宕机后消费者服务直接异常-----》Hystrix熔断器来解决
            ........
         */
        //String url = "http://localhost:9091/user/findUserById/" + id;
​
        //第二次的url
       /* List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        String url =  instances.get(0).getUri() + "/user/findUserById/" + id;*/
​
        //第三次url
        String url = "http://user-service/user/findUserById/" + id;
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }
​
    /**
     * @Author: guodong
     * @Date: 15:59 2020/9/19
     * @Parms [id]
     * @ReturnType: com.itheima.pojo.User
     * @Description: 默认服务降级方法
     *                      1.返回值类型必须与原方法一致
     *                      2.参数列表必须与原方法一致
    */
    public User fallback(Integer id){
        User user = new User();
        user.setId(id);
        user.setNote("默认服务降级方法...");
        return user;
    }
​
    /**
     * @Author: guodong
     * @Date: 16:06 2020/9/19
     * @Parms [id]
     * @ReturnType: com.itheima.pojo.User
     * @Description: 当前类所有方法的默认服务降级方法要求: 1.返回值类型必须与原方法一致;2.不能有参数列表
    */
    public User defaultFall(){
        User user = new User();
        user.setNote("当前类默认服务降级方法...");
        return user;
    }
​
    /**
     * @Author: guodong
     * @Date: 11:16 2020/9/19
     * @Parms []
     * @ReturnType: java.util.List<org.springframework.cloud.client.ServiceInstance>
     * @Description: 获取服务列表
    */
    @GetMapping("getInstances")
    public List<ServiceInstance> getInstances(){
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        return instances;
    }
}
5. 原理分析
# 配置熔断策略:
hystrix:
  command:
    default:
      circuitBreaker:
        forceOpen: false #强制打开熔断器 默认false关闭的
        requestVolumeThreshold: 20 # 熔断触发最小请求次数,默认值是20
        errorThresholdPercentage: 50 # 触发熔断错误比例阈值,默认值50%
        sleepWindowInMilliseconds: 5000 # 熔断后休眠时长,默认值5秒
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1000 #熔断超时设置,默认为1秒

image-20200919162213977.png

服务降级:

调用默认的服务降级方法,但是对于正常的访问资源不会降级。

服务的熔断:

调用默认的服务降级方法,区别是即使可以正常访问的资源都会进入服务降级方法

场景:

  • 在userController中添加判断如果id=1抛出异常
  • 测试---》请求id=1的资源5次,请求id=2的资源,验证是否可以请求成功?
  • 测试---》请求id=1的资源20次,请求id=2的资源,验证是否可以请求成功?
6. 监控使用(了解)

步骤:

  1. 导入hystrix监控依赖、导入actuator暴露健康指标依赖
  2. 在启动类添加开启监控注解
  3. 在配置文件中添加暴露所有指标
  4. 测试访问

过程:

  • 依赖

    <!--监控坐标依赖-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
            </dependency>
            <!--actuator依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
    
  • 开启注解

    @SpringCloudApplication //一个顶三
    @EnableHystrixDashboard //开启熔断器监控
    public class ConsumerServiceApplication {
        public static void main(String[] args) {
            SpringApplication.run(ConsumerServiceApplication.class, args);
        }
        @Bean
        @LoadBalanced //使用ribbon进行负载调用
        public RestTemplate restTemplate(){
            return new RestTemplate();
        }
    }
    
  • 暴露指标

    #暴露所有的指标
    management:
      endpoints:
        web:
          exposure:
            include: '*'
    
  • 访问

    http://localhost:8081/hystrix

image-20200921092229943.png