Spring Cloud Hystrix服务容错保护

spring Cloud Hystrix实现了断路器、线程隔离等一系列保护功能,避免级联故障,
具备服务降级,服务熔断,线程和信号隔离,请求还车,请求合并以及服务监控的强大功能。
服务降级fallback 服务降级,不可用了向调用方返回备选方案
服务熔断breaked 直接拒绝访问,然后服务降级再返回友好提示
服务限流 高并发操作

eureka-server功能:服务注册中心,端口号1111
hello-service工程:HELLO-SERICE的服务单元,两个实例启动端口分别是8081,8082
ribbon-consumer工程:使用Ribbon实现服务消费者,端口号9000
再未加入熔断器之前,关闭8081实例,服务器使用轮询负载均衡,导致消费者请求一次成功,一次返回状态码500
开始r导入springcloud Hystrix
再ribbon-consumer工程中导入依赖

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>

在启动类上加注解@Enable-CircuitBreaker注解开启断路器功能,或者

@SpringCloudApplication注解包含@Enable-CircuitBreaker
//开启断路器功能
@EnableCircuitBreaker
//@SpringCloudApplication
@EnableDiscoveryClient
//该应用注册为Eureka客户端
@SpringBootApplication
//配置负载均衡算法
//@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MyselfRule.class)
public class RibbonConsumerApplication {
    @Bean
    @LoadBalanced
    //开启客户端负载均衡
    RestTemplate restTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(RibbonConsumerApplication.class, args);
    }

}

增加service模块

@Service
public class HelloService {
    @Autowired
    RestTemplate restTemplate;
    @HystrixCommand(fallbackMethod = "helloFallback")
    public String helloService(){
        return restTemplate.getForEntity("http://HELLO-SERVICE/hello",String.class).getBody();
    }
    public String helloFallback(){
        return "error";
    }

}

把service模块注入controller,
这时候再调用去消费服务的时候,有一个服务提供者停掉了,会返回 error
服务消费者熔断机制。
我们现在对hello-service进行改造,让线程等待几秒钟,Hystriix默认超时时间是2000毫秒。

@RestController
public class HelloController {
    private final Logger logger=Logger.getLogger(getClass());

    @Autowired
    private DiscoveryClient client;
    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String index() throws InterruptedException {
       //让线程等待几秒钟
        ServiceInstance localServiceInstance = client.getLocalServiceInstance();
        int sleeptime=new Random().nextInt(3000);
        logger.info("sleepTime"+sleeptime);
        Thread.sleep(sleeptime);
        logger.info("/hello,host:"+localServiceInstance.getHost()+",service_id:"+localServiceInstance.getServiceId());
        return "Hello World";
    }
}

等待时间超过2000的时候就会返回error

原创文章 41 获赞 11 访问量 1496

猜你喜欢

转载自blog.csdn.net/weixin_44038332/article/details/105174996
今日推荐