1.消费者添加依赖
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-netflix-hystrixartifactId>
- dependency>
2.消费者Application上添加注解,驱动Hystrix
- @EnableCircuitBreaker
- @SpringBootApplication
- public class ProductApplication {
- public static void main(String[] args) {
- SpringApplication.run(ProductApplication.class, args);
- }
3.在服务提供者添加接口
模拟服务提供者出现错误
-
- @RestController
- public class HystrixController {
- private static Long MaxSleepTime = 5000L;
-
- // 超时
- @RequestMapping("/timeout")
- public ResultMessage TestError() {
- try {
- Thread.sleep((long) (MaxSleepTime * Math.random()));
- } catch (InterruptedException e) {
- System.out.println("服务端在延时发生了异常");
- e.printStackTrace();
- }
- return new ResultMessage(true, "延时时间较短,没有触发超时异常,延时时间:" + MaxSleepTime);
- }
-
- //模拟发生了异常
- @GetMapping("/exp/{msg}")
- public ResultMessage exp(@PathVariable("msg") String msg) {
- if (msg.equals("hello")) {
- return new ResultMessage(true, msg);
- } else {
- throw new RuntimeException();
- }
- }
- }
4.消费者增加 远程调用服务
- @Service
- public class UserService implements UserFacae {
- @Autowired
- RestTemplate restTemplate;
-
- @HystrixCommand(fallbackMethod = "fallbackTimeOut")
- @Override
- public ResultMessage timeout() {
- return restTemplate.getForObject("http://USER/timeout", ResultMessage.class);
- }
-
- @HystrixCommand(fallbackMethod = "fallbackError")
- @Override
- public ResultMessage accureError(String msg) {
- return restTemplate.getForObject("http://USER/exp/"+msg, ResultMessage.class);
- }
-
- public ResultMessage fallbackTimeOut() {
- return new ResultMessage(false, "该接口延时时间过长,引发了超时异常,启动消费者的异常处理方法");
- }
-
- public ResultMessage fallbackError(String msg) {
- return new ResultMessage(false, "发生异常,msg参数是:"+msg);
- }
- }
和controller和service
因为是通过resttemple远程调用的服务器的接口,所以这里不写interface,写 Facae
- public interface UserFacae {
- public ResultMessage timeout();
-
- public ResultMessage accureError(String msg);
- }
- @RestController
- public class UserController {
- @Autowired
- UserFacae userFacae;
-
- @RequestMapping("timeout")
- public ResultMessage timeout() {
- return userFacae.timeout();
- }
-
- @RequestMapping("/error/{msg}")
- public ResultMessage takeError(@PathVariable String msg) {
- return userFacae.accureError(msg);
- }
- }
会有触发延时,因为时长随机的,所以会随机超时,引发超时异常,由消费端的fallbackTimeOut()方法捕获。
访问localhost:7301/error/hello123
如果参数是hello 不引发异常
如果参数是hello123 会引发异常,由消费端的fallbackError(String msg)方法捕获,注意,因为引发fallbackError(String msg)的accureError(String msg) 方法,有一个string类型的参数,所以异常处理参数也一定要有string类型的参数。