springcloud使用(四) 熔断器Hystrix

熔断器的概念和优点参考 springcloud(四):熔断器Hystrix, 讲的很详细

基于feign的Hystrix

在前面的feign的消费者的项目上面改改就ok

  1. application.properties中添加 feign.hystrix.enabled=true, 开启服务熔断
  2. 编写helloService接口的实现类HelloServiceFallBack
@Service
public class HelloServiceFallBack implements HelloService {
    @Override
    public String hello(Map map) {
        // 可以进行一些错误记录, 将未完成的业务可能人工干预处理
        return ">>>>>>>>>>>>>调用服务失败, 参数:"+map.toString();
    }
}
  1. 在helloService的注解FeignClient中添加fallback = HelloServiceFallBack.class, 表示调用服务异常后回调执行HelloServiceFallBack的业务
    @FeignClient(value ="spring-cloud-eureka-producer",fallback = HelloServiceFallBack.class)
  2. 服务生产者的代码中抛一个异常
@RestController
public class ApiHello {
    /*@Autowired
    private LoadBalancerClient loadBalancerClient;*/

    @RequestMapping(value = "/hello")
    public String sayHello(HttpServletRequest request) throws IllegalAccessException {
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        if(age.equals("23")){
            throw new IllegalAccessException("我出错了xox");
        }
        System.out.println("我是9000");
        return JSON.toJSONString("hello,"+name);
    }
}
  1. 启动消费者和服务者, 请求参数中加入age参数, 发现age=23的时候, 消费者回调了HelloServiceFallBack的业务
基于Ribbon的Hystrix

在ribbon的consumer上修改

  1. 新增依赖spring-cloud-starter-netflix-hystrix

            org.springframework.cloud
            spring-cloud-starter-netflix-hystrix
        
  1. 启动类上添加注解 @EnableHystrix
  2. controller中加入fallback
@RequestMapping(value = "/consumer/hello")
    @HystrixCommand(fallbackMethod = "fallBackre")
    public String hello(HttpServletRequest request) throws JsonProcessingException {
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        MultiValueMap map= new LinkedMultiValueMap<>();
        map.add("name",name);
        map.add("age",age);
        return this.restTemplate.postForObject("http://spring-cloud-eureka-producer/hello",map,String.class);
    }

    /**
     * 服务异常回调方法
     * @return
     */
    public String fallBackre(HttpServletRequest request){
        String name = request.getParameter("name");
        return ">>>>>>>>>>>>>调用服务失败, 参数:"+name;
    }

这是方法级别的回调, 注意方法参数值

  1. 完毕, 启动服务者个消费者, 当age=23时, 调用fallBackre方法
    over

你可能感兴趣的:(springcloud使用(四) 熔断器Hystrix)