六、Hystrix详解一、Hystrix的基本使用

Hystrix是Netflix开源的一款容错框架,包含常用的容错方法:线程池隔离、信号量隔离、熔断、降级回退。
在高并发访问下,系统所依赖的服务的稳定性对系统的影响非常大,依赖有很多不可控的因素,比如网络连接变慢,资源突然繁忙,暂时不可用,服务脱机等。
我们要构建稳定、可靠的分布式系统,就必须要有这样一套容错方法。

6.1. Hystrix的基本使用


1、创建一个Eureka Client项目futurecloud-hystrix


2、添加依赖


<!--添加Hystrix依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.0.2.RELEASE</version>
</dependency>

3、在主函数上添加注解@EnableCircuitBreaker,启动Hystrix


package com.futurecloud.hystrix;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 * Hello world!
 *
 */
@SpringBootApplication
@EnableEurekaClient//声明为eureka 客户端
@EnableFeignClients //启动Feign
@EnableCircuitBreaker //启动Hystrix
public class FuturecloudHystrixApplication
{
    @Bean  //相当于xml中的bean标签,主要是用于调用当前方法获取到指定对象
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
    public static void main( String[] args )
    {

        SpringApplication.run(FuturecloudHystrixApplication.class,args);
    }
}

4、Feign 接口,(可以不使用)


package com.futurecloud.hystrix.feignClient;

import com.futurecloud.hystrix.bean.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@FeignClient(name = "futurecloud-user")   //通过注解指定依赖服务
public interface FeignClientInterfaces {

   @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
   User getUserById(@PathVariable("id") Long id);

    @GetMapping("/getUser/{id}")
    User getUser(@PathVariable("id") Long id);

    @RequestMapping(value = "/find/user/{id}",method = RequestMethod.POST)
    User findUserById(@PathVariable("id") Long id);
}

5、使用Hystix熔断器


package com.futurecloud.hystrix.controller;

import com.futurecloud.hystrix.bean.User;
import com.futurecloud.hystrix.feignClient.FeignClientInterfaces;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import feign.Param;
import feign.RequestLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
public class FuturecloudHystrixController {

    @Autowired
   private FeignClientInterfaces feignClientInterfaces;

    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    public User getUserById(@PathVariable("id") Long id){
        User user = feignClientInterfaces.getUserById(id);
        return user;
    }

    @GetMapping("/getUser/{id}")
    public User getUser(@PathVariable("id") Long id){
        User user = feignClientInterfaces.getUser(id);
        return user;
    }

    /**
     * 使用Hystrix熔断器,当调用findUserById失败后,调用forbackFindUserById方法
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "forbackFindUserById")
    @RequestMapping(value = "/find/user/{id}",method = RequestMethod.GET)
    public User findUserById(@PathVariable("id") Long id){
        User user = feignClientInterfaces.findUserById(id);
        int a = 4/0;
        return user;
    }

    public User forbackFindUserById(Long id){
        User user = new User();
        user.setId(-400L);
        user.setUsername("hystrix-fallback");
        user.setMail("hystrix-fallback@sina.com");
        user.setPhone("13838384381");
        user.setCreateDate(new Date());
        return  user;
    }
}

使用这个注解@HystrixCommand来定义Hystrix的熔断器,查看HystrixCommand源码,这个注解有10个属性,
我们使用fallbackMethod属性,来指定接口调用失败后执行的方法。
HystrixCommand源码如下:


package com.netflix.hystrix.contrib.javanica.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface HystrixCommand {
    String groupKey() default "";
    String commandKey() default "";
    String threadPoolKey() default "";
    String fallbackMethod() default "";
    HystrixProperty[] commandProperties() default {};
    HystrixProperty[] threadPoolProperties() default {};
    Class<? extends Throwable>[] ignoreExceptions() default {};
    ObservableExecutionMode observableExecutionMode() default ObservableExecutionMode.EAGER;
    HystrixException[] raiseHystrixExceptions() default {};
    String defaultFallback() default "";
}

6、application.yml配置如下:


server:
  port: 8906
spring:
  application:
    name: futurecloud-hystrix
#将此服务注册到eureka 服务上
eureka:
  client:
    serviceUrl:
      defaultZone: http://user:123@localhost:10000/eureka
  instance:
    prefer-ip-address: true  #将注册到eureka服务的实例使用ip地址

#Feign日志的配置
logging:
  level:
    com.futurecloud.feign.interfaces.CustomFeignClient: DEBUG

启动eureka 服务futurecloud-service,
启动服务提供者服务futurecloud-user,
启动此服务futurecloud-hystrix
访问http://localhost:8906/order/20 ,成功访问
将服务futurecloud-user关掉,再一次访问http://localhost:8906/order/20,进入到了@HystrixCommand指定的方法forbackFindUserById

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值