【Spring Cloud】--服务容错保护Hystrix

简言之Hystrix的作用就是,在服务调用失败的时候,会返回一个错误的相应,而不是长时间的等待。

快速入门:
同样使用http://blog.csdn.net/wangpengzhi19891223/article/details/78840646中的例子对服务进行改造:

1,consumer中引入依赖:

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

这里写图片描述

1,ConsumerApplication.java 中使用注解开启断路器功能:

@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication {

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

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

新增HelloService类:

@Service
public class HelloService {
    private final Logger logger = Logger.getLogger(HelloService.class);
    @Autowired
    RestTemplate restTemplate;
    @HystrixCommand(fallbackMethod = "helloFallback")
    public String helloService(){
        long start = System.currentTimeMillis();
        String result =  restTemplate.getForEntity("http://HELLO-SERVICE/hello",String.class).getBody();

        logger.info("耗时:" + (System.currentTimeMillis() - start));
        return  result;
    }
    public String helloFallback(){
        return "error";
    }
}

改造ConsumerController,注入service实例:

@RestController
public class ConsumerController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private HelloService helloService;

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

同样给出application.properties中的内容:

spring.application.name=ribbon-consumer
server.port=9000
eureka.client.serviceUrl.defaultZone = http://peer1:1111/eureka/

启动项目,并关闭注册中心,访问:http://localhost:9000/consumer 返回:error,说明调用到了我们写断路器方法。


改造一下service工程中的提供服务的hello方法:

@RestController
public class HelloController {

    private final Logger logger = Logger.getLogger(HelloController.class);
    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String index() throws Exception{
        ServiceInstance instance = client.getLocalServiceInstance();
        int sleepTime = new Random().nextInt(3000);
        logger.info("sleeptime"+sleepTime);
        Thread.sleep(sleepTime);
        logger.info("host:"+instance.getHost()+instance.getServiceId()+":"+instance.getPort());
        return "New Hello world server!";
    }
}

当随机数休眠时间大于2000时,返回error
当小于2000的时候返回:New Hello world server!

猜你喜欢

转载自blog.csdn.net/wangpengzhi19891223/article/details/78902569