Spring Cloud (五)、服务容错保护Hystrix(入门)

Spring Cloud Hystrix通过控制那些访问远程系统、服务和第三方库的节点,从而对延迟和故障提供更强大的容错功能。

我们需要使用之前的一些内容作为基础,在这里我们需要启动的工程有如下一些:

  • eureka-server工程:服务注册中心,端口为1111。

       参考:Spring Cloud (一)、搭建服务注册中心

  • spring-boot-hello工程:HELLO-SERVICE的服务单元,两个实例启动端口分别为8081和8082。

       参考:Spring Cloud (二)、向注册中心注册服务提供者

  • ribbon-consume工程:使用Ribbon实现的服务消费者,端口为9000。

       参考:Spring Cloud (四)、服务发现与服务消费

测试:在未加入断路由之前,关闭8081的实例:

       浏览器发送GET请求到http://localhost:9000/ribbon-consume,页面上显示如下:

      用postman进行GET访问 http://localhost:9000/ribbon-consume,获得下面的输出:

下面我们引入Spring Cloud Hystrix:

1、在ribbon-consume工程的pom.xml的dependency节点中引入spring-cloud-starter-hystrix依赖:

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

 2、在ribbon-consume工程的主类RibbonConsumeApplication中使用@EnableCircuitBreaker注解打开断路由的功能:

/**
 * @author HDN
 * @date 2019/6/16 14:29
 */
@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class RibbonConsumeApplication {

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

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

}

注意:这里还可以使用Spring Cloud应用中的@SpringCloudApplication注解来修饰应用主类,该注解的具体定义如下:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public @interface SpringCloudApplication {

}

        可以看到,该注解中包含了上述我们所引用的三个注解,这就意味着一个Spring Cloud标准应用应包含Spring Boot注解、服务发现以及断路器。

3、改造服务消费方式,新增HelloService类,注入RestTemplate实例。然后将在ConsumerController中对RestTemplate的使用迁移到helloService函数中,最后,在helloService 函数上增加@HystrixCommand注解来指定回调方法: 

/**
 * @author HDN
 * @date 2019/6/18 20:30
 */
@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";
    }
}

4、修改ConsumerController类,注入上面实现的HelloService实例,并在helloConsumer中进行调用:

/**
 * @author HDN
 * @date 2019/6/16 14:29
 */
@RestController
public class ConsumerController {

    @Autowired
    HelloService helloService;

    @RequestMapping(value="/ribbon-consumer",method= RequestMethod.GET)
    public String helloConsumer(){
        return helloService.helloService();
    }
}

测试:重新启动之前关闭的8081端口的hello-service,确保此时注册中心、两个HELLO-SERVICE以及ribbon-consume均已启动,访问http://localhost:9000/ribbon-consume可以轮询两个HELLO-SERVICE并返回一些文字信息。此时,我们再次断开8081的HELLO-SERVICE,然后访问http://localhost:9000/ribbon-consume,当轮询到8081服务时,输出内容为error,不再是之前的错误内容,表示Hystrix的服务回调生效。

以上是通过断开具体的服务实例来模拟某个节点无法访问的情况。

-----------------------------------------------------------------------------------------------------------

接下来通过模拟服务阻塞(长时间未响应)的情况:

1、对HELLO-SERVICE的/hello接口进行修改:添加了让处理线程等待几秒钟的代码。

/**
 * @author HDN
 * @date 2019/6/16 14:34
 */
@RestController
public class HelloController {

    private static Logger logger = Logger.getLogger(String.valueOf(HelloController.class));

    @Qualifier("eurekaRegistration")
    @Autowired
    private Registration registration;


    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value="/hello",method = RequestMethod.GET)
    public String hello() throws InterruptedException {
        /*参考书中这个getLocalServiceInstance()目前已过时,我们可以使用Registration根据服务名获取注册了该服务名的所有实例*/
        /*ServiceInstance instance = client.getLocalServiceInstance();*/
        List<ServiceInstance> list = client.getInstances(registration.getServiceId());
        ServiceInstance instance = null;
        if (list != null && list.size() > 0) {
            for(ServiceInstance itm : list){
                instance =  itm;
            }
        }

        //让处理线程等待几秒钟
        int sleepTime = new Random().nextInt(3000);
        logger.info("sleepTime:"+sleepTime);
        Thread.sleep(sleepTime);

        String result = "/hello, host:port=" + instance.getPort()  + ", "
                + "service_id:" + instance.getServiceId();
        logger.info(result);
        return "HELLO WORLD";
    }
}

       通过Thread.sleep()函数可让/hello接口的处理线程不是马上返回内容,而是在阻塞几秒之后才返回内容。由于Hystrix默认超时时间为1000毫秒(可在HystrixCommandProperties类中查看default_executionTimeoutInMilliseconds属性值),所以这里采用了0至3000的随机数以让处理过程中有一定概率发生超时来触发断路器。

2、为了更准确地观察断路器的触发,在消费者调用函数中做一些时间记录:

/**
 * @author HDN
 * @date 2019/6/18 20:30
 */
@Service
public class HelloService {
    private static Logger logger = Logger.getLogger(String.valueOf(HelloService.class));

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "helloFallback",commandKey = "helloKey")
    public String helloService(){
        long start =System.currentTimeMillis();

        String result =  restTemplate.getForEntity("http://HELLO-SERVICE/hello",String.class).getBody();

        long end = System.currentTimeMillis();

        logger.info("Spend time:"+(end-start));
        return result;
    }

    public String helloFallback(){
        return "error";
    }
}

测试:重新启动HELLO-SERVICE和ribbon-consume的实例,连续访问http://localhost:9000/ribbon-consumer几次,我们可以观察到,当ribboon-consume的控制台输出Spend time 大于1000的时候,页面就会返回error,即服务消费者因调用的服务超时从而触发熔断请求,并调用回调逻辑返回结果。

-----------------------------------------------------总结--------------------------------------------------

总结:@HystrixCommand注解定义Hystrix命令的实现;

           @HystrixCommand(fallbackmethod="")中的fallbackmethod来指定具体的服务降级实现方法。

           在使用注解来定义服务降级时,我们需要将具体的Hystrix命令与fallback实现函数定义在同一个类中,并且fallbackmethod的值必须与实现fallback方法的名字相同。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值