六Hystrix详解一Hystrix的基本使用

Posted makyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了六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

以上是关于六Hystrix详解一Hystrix的基本使用的主要内容,如果未能解决你的问题,请参考以下文章

Hystrix使用详解

Hystrix使用详解

Hystrix使用及其配置详解

Hystrix使用及其配置详解

Spring Cloud Spring Boot mybatis分布式微服务云架构-hystrix参数详解

Spring Cloud Spring Boot mybatis分布式微服务云架构-hystrix参数详解