springcloud-hystrix

为了保证高可用性,单个服务通常会集群部署。由于网络原因或者自身的原因,服务并不能保证100%可用,如果单个服务出现问题,调用这个服务就会出现线程阻塞,此时若大量的请求涌入,Servlet容器的线程资源会被消耗完毕,导制服务瘫痪。服务与服务之间的依赖性,故障会传播,会对整个微服务系统造成灾难性的严重后里,这就是服务故障的“雪崩”效应。

Hystrix

Netflix开源了Hystrix组件,实现了断路器模式。

对于特定的服务的调用的不可用达到一个阈值(Hystric是5秒20次)断路器将会被打开。

实战

1、启动eureka-server,启动service-hi工程,它的端口为8762.

2、在ribbon中使用断路器

(1)改造service-ribbon工程的代码,首先在pom.xml文件中加入spring-cloud-starter-netflix-hystrix的起步依赖

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

(2)在程序的启动类ServiceRibbonApplication加@EnableHystrix注解开启hystrix

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableHystrix
public class ServiceRibbonApplication {

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

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

}

(3)改造HelloService类,在hiService方法上加上@HystrixCommand注解。该注解对该方法创建了熔断器的功能,并指定了fallbackMethod熔断方法,熔断方法直接返回一个字符串。

@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hiError")
    public String hiService(String name) {
        return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
    }

    public String hiError(String name) {
        return "hi,"+name+",sorry,error!";
    }

}

(4)启动service-ribbon工程,当我们访问http://localhost:8764/hi?name=xxx

(5)此时关闭service-hi工程,当我们再访问http://localhost:8764/hi?name=xxx

2、Feign中使用断路器

(1)Feign是自带断路器的,在D版本的Spring Cloud之后,它没有默认打开。需要在配置文件中配置打开它,在配置文件加以下代码:

feign.hystrix.enabled=true

(2)基于service-feign工程进行改造,只需要在FeignClient 的SchedualServiceHi接口的注解中加上fallback的指定类就行了。

@FeignClient(value = "service-hi",fallback = SchedualServiceHiHystric.class)
public interface SchedualServiceHi {
    @RequestMapping(value = "/hi",method = RequestMethod.GET)
    String sayHiFromClientOne(@RequestParam(value = "name") String name);
}

(3)SchedulaServiceHiHystrix需要实现SchedualServiceHi接口,并注入到Ioc容器中。

@Component
public class SchedualServiceHiHystric implements SchedualServiceHi {
    @Override
    public String sayHiFromClientOne(String name) {
        return "sorry "+name;
    }
}

(4)启动service-feign工程,浏览器打开http://localhost:8765/hi?name=xxx

猜你喜欢

转载自blog.csdn.net/CHS007chs/article/details/83504592