首先,要在POM里加入如下配置:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
实现一个HelloService:
package com.sc.consumerribbon.service;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class HelloService {
@Autowired
private RestTemplate restTemplate;
private String serviceName = "http://HELLO-SERVICE/hello/";
@HystrixCommand(fallbackMethod = "helloFallback")
public String getHello() {
return this.restTemplate.getForEntity(this.serviceName, String.class).getBody();
}
public String helloFallback() {
return "error\n";
}
}
关键是其中的 @HystrixCommand(fallbackMethod = "helloFallback") ,意思是调用HELLO-SERVICE失败时,会执行helloFallback方法,返回error。
然后,在真正的Controller层实现对HelloService的调用:
package com.sc.consumerribbon.controller;
import com.sc.consumerribbon.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConsumerController {
@Autowired
private HelloService helloService;
@GetMapping("/ribbon-consumer")
public String helloConsumer() {
return this.helloService.getHello();
}
}
注意,还要在Application层面加入注解@EnableCircuitBreaker
@EnableCircuitBreaker
@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerRibbonApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
实现效果如下:
明显的,远端服务接口HELLO-SERVICE随机休眠,如果超过1000毫秒,触发断路器,则会执行fallback方法,放回error。如果随机休眠在1000毫秒以内,则正常返回结果!