springCloud的使用04-----熔断器hystrix的使用

1. restTemplate+ribbon使用hystrix

  1.1 引入依赖

<!-- 配置hystrix断路器 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

  1.2 在需要熔断的方法上添加注解

@Service
public class HiService {

    @Autowired
    RestTemplate restTemplate;
    
    //需要熔断的方法
    @HystrixCommand(fallbackMethod="hiError")//熔断后执行的方法
    public String sayHi() {
        return restTemplate.getForObject("http://SERVICE-HI/info", String.class);
    }
    
    //熔断后执行的方法
    public String hiError() {
        return "sorry hi error";
    }
}

  1.3 在启动类中声明使用hystrix

@SpringBootApplication
@EnableDiscoveryClient//向服务中心注册
@RestController
@EnableHystrix//启用熔断机制
public class ConsumerRibbon {
 
    @Autowired
    private HiService hiService;
    
    public static void main(String[] args) {
        SpringApplication.run(ConsumerRibbon.class, args);
    }
    
    @Bean
    @LoadBalanced//使用这个restTemplate开启负载均衡
    RestTemplate initRestTemplate(){
        return new RestTemplate();
    }
    
    @RequestMapping("info")
    public String hiConsumer() {
        String response=hiService.sayHi();
        return response;
    }
}

  1.4 启动注册中心和cloud-consumer-ribbon,访问http://localhost:8764/info 返回sorry hi error

    启动service-hi,访问http://localhost:8764/info 返回hello eureka client 8762

2 feign使用hystrix

  2.1 feign自带熔断器,无需导入hystrix的依赖,但是需要导入以下依赖,否则回报java.lang.NoClassDefFoundError: com/netflix/hystrix/contrib/javanica/aop/aspectj/HystrixCommandAspect错误

<dependency>
    <groupId>com.netflix.hystrix</groupId>
    <artifactId>hystrix-javanica</artifactId>
</dependency>

  2.2 在配置文件中启用hystrix,默认是关闭的

feign: 
 hystrix: 
  enabled: true

  2.3 指定熔断后要执行的类

@FeignClient(value="service-hi",fallback=HiServiceHystric.class)//指定调用哪个服务提供者,指定熔断后的执行的类
public interface IHiService {
    
    @RequestMapping(value="/info",method=RequestMethod.GET)//指定调用服务提供者的哪个接口
    String info();
    
    @RequestMapping(value="/info",method=RequestMethod.GET)//指定调用服务提供者的哪个接口
    String hi();
}

  2.4 指定熔断后要执行对应的方法

@Component
public class HiServiceHystric implements IHiService {

    //熔断后执行相应的方法
    public String info() {
        return "sorry info feign";
    }

    public String hi() {
        return "sorry hi feign";
    }
}

  2.5 在启动类中声明启动hystrix

@EnableHystrix

  2.6 启动注册中心和cloud-consumer-feign,访问http://localhost:8765/info 返回sorry info feign

    启动service-hi,访问http://localhost:8765/info 返回hello eureka client 8762

猜你喜欢

转载自www.cnblogs.com/lifeone/p/9010125.html
今日推荐