Hystrix断路器与服务降级

Hystrix:

Hystrix的作用

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

Hystrix中的重要概念

服务雪崩

		在微服务中,服务调用关联很多,一个请求可能需要多个服务才能实现,比如一次请求需要调用A、B、C、D、E、F这五个服务,而这五个服务有需要调用其他服务。
		在这时,如果有服务发生异常,比如D服务发生异常,请求就会阻塞,用户接受不到响应,tomcat的这个线程也不会释放。而用户得不到响应,势必会再次发送请求,于是用户请求越来越多,越来越多的请求会阻塞。
		服务器支持的线程和并发数有限,请求一直阻塞,回导致服务器资源耗尽,导致其他服务也不可用,形成雪崩效应。

服务降级

					服务器繁忙或者拥堵时,不让客户端等待而是直接返回一个友好的提示(比如:服务器繁忙,请稍后重试)

服务熔断

					当服务器达到最大访问数之后,直接拉闸,拒绝访问,返回一个友好的提示。

服务限流

				禁止秒杀等大规模拥挤的现象,排队进行,一秒钟N个,有序进行。

Hystrix案例

		1.建立Hystrix模块
		2.引入依赖  
<dependencies>
    <!-- hystrix -->
<!--
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
-->
    <!--eureka-client-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
        <groupId>com.krisswen.cloud</groupId>
        <artifactId>cloud-api-commons</artifactId>
        <version>${project.version}</version>
    </dependency>
</dependencies>

3.编写application.yml配置文件

server:
  port: 8001
spring:
  application:
    name: cloud-payment-service  #服务名称
eureka:
  client:
    # 注册进 Eureka 的服务中心
    register-with-eureka: true
    # 检索 服务中心 的其它服务
    fetch-registry: true
    service-url:
      # 设置与 Eureka Server 交互的地址
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

4.编写启动类

@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker //开启服务熔断
public class CloudHystrixApplication {
    public static void main(String[] args) {
        SpringApplication.run(CloudHystrixApplication.class,args);
    }
}


5.编写controller

package com.usian.controller;

import com.usian.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class PaymentController {

    @Autowired
    PaymentService paymentService;

    @Value("${server.port}")
    private String prot;

    /**
     * 可以正常访问的方法
     * @param id
     * @return
     */
    @GetMapping("/payment/hystrix/ok/{id}")
    public String ok(@PathVariable("id") Integer id){
        log.info("okokok...");
        return paymentService.ok(id);
    }

    @GetMapping("/payment/hystrix/timeout/{id}")
    public String timeOut(@PathVariable("id") Integer id){
        log.info("timeOut....");
        return paymentService.timeOut(id);
    }
}

//localhost:8001/payment/hystrix/ok/1
//localhost:8001/payment/hystrix/timeout/1

6.直接编写service,这里为了方便就不连接数据库了,直接写方法

package com.usian.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {

    /**
     * 可以正常访问的方法
     * @param id
     * @return
     */
    public String ok(Integer id){
        return "线程池"+Thread.currentThread().getName()+"ok,id:"+id;
    }

    /**
     * 超时访问的方法
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "timeoutHandler",commandProperties = {
            //设置峰值,超过 3 秒,就会调用兜底方法,这个时间也可以由feign控制
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String timeOut(Integer id){
        int interTime = 3;
        try {
            TimeUnit.SECONDS.sleep(interTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "线程池"+Thread.currentThread().getName()+"timeOut,id:"+id+",耗时"+interTime+"秒钟";
    }

    //定义服务出现异常兜底的方法
    public String timeoutHandler(Integer id){
        return "服务异常,请重试......";
    }
}

注意:Thread.currentThread().getName() : 表示获取当前代码被调用的线程的名字。
@HystrixCommand : 开启服务熔断、降级
fallbackMethod:服务熔断、降级后兜底的方法名。

调用下正常访问的方法
在这里插入图片描述
再调用超时三秒的方法(ribbon默认超时时间是1秒)

在这里插入图片描述
成功。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值